package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.houbb.paradise.common.util.StringUtil;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsUserBusinessDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.BmsUserBusinessRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.BusinessRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.SearchCodeRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupBuy.searchCode.Code;
import com.syni.mdd.yhd.common.all.dto.reponseDto.groupMessage.ConsumerUserRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.BusinessOrderDetailRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.BusinessOrderHomeRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.OrderManagerDetail;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.OrderManagerList;
import com.syni.mdd.yhd.common.all.dto.reponseDto.verRecord.VerRecordRpDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.groupBuy.GroupBuyUseReDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.order.BusinessOrderDetailReDto;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsDxGroupChat;
import com.syni.mdd.yhd.common.all.entity.permission.PermessionCodeUtils;
import com.syni.mdd.yhd.common.all.entity.permission.PermissionCode;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.listen.businessClaim.BusinessClaimEvent;
import com.syni.mdd.yhd.common.all.listen.shopAssistant.AssistantEvent;
import com.syni.mdd.yhd.common.all.listen.video.VideoEvent;
import com.syni.mdd.yhd.common.all.service.groupChat.BmsUserChatService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.RestTemplateUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.vo.rp.userBusiness.GetVerRecordDetailsRpVo;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mdd.sjb.common.dxshapp.apiUserChannel.TransferManagerDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.CertificationBusinessDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiOrder.GetByBusinessOrderForDataBankDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.sjb.common.datatreasure.DxshUserChannelRestService;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
@Log4j2
public class BmsUserBusinessService extends BaseService<BmsUserBusiness, Integer> {

    private Logger logger = LoggerFactory.getLogger(getClass());
    //注册
    final static int registerCodeType = 101;
    //登录
    final static int loginCodeType = 102;
    //添加店员
    final static int addAssistantCodeType = 103;

    //否为第一次登录
    final static int notFirstLogin = 0;
    //是为第一次登录
    final static int isFirstLogin = 1;
    //没有任何类型
    final static int noUserBusinessType = 0;
    //商户类型
    final static int userBusinessType = 2;
    //店员类型
    final static int assistantType = 3;

    final static String defaultPwd = "";

    @Autowired
    BmsUserBusinessDao bmsUserBusinessDao;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsDxUserPermissionService bmsDxUserPermissionService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsUserVideoService bmsUserVideoService;

    @Autowired
    BmsUserBusinessFocusService bmsUserBusinessFocusService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsBusinessinfoService bmsBusinessinfoService;

    @Autowired
    BmsBusinessLabelService bmsBusinessLabelService;

    @Autowired
    BmsBusinessTypeRelationService bmsBusinessTypeRelationService;

    @Autowired
    BmsUserLoginLogService bmsUserLoginLogService;

    @Autowired
    BmsGroupBuyTemplateService bmsGroupBuyTemplateService;

    @Autowired
    BmsDxGroupChatService bmsDxGroupChatService;

    @Autowired
    BmsUserChatService bmsUserChatService;

    @Autowired
    BmsBusinessTypeService bmsBusinessTypeService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsSuperPwdService bmsSuperPwdService;

    @Autowired
    BmsBusinessFlowService bmsBusinessFlowService;

    @Autowired
    BmsAgentService bmsAgentService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsBusinessVerRecordService bmsBusinessVerRecordService;

    @Autowired
    DxshUserChannelRestService dxshUserChannelRestService;

    @Override
    public BmsUserBusinessDao getBaseDao() {
        return bmsUserBusinessDao;
    }

    public Map<String, Object> userRegisterBussiness(ParamsMap paramsMap) {
        String phone = paramsMap.get("phone").toString();
        String identifyCode = paramsMap.get("identify_code").toString();
        String password = paramsMap.getString("password");
        if(StringUtil.isBlank(password)){
            password = defaultPwd;
        }
        BmsUser bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
        if(bmsUser != null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_BUSINESS_EXIST,"该手机号已被使用,请使用其他手机号注册");
        }
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,registerCodeType)){
            return ResultMapHelper.result(ResultCode.CODE_IDENTIFY_CODE_ERROR,ResultMsg.CODE_IDENTIFY_CODE_ERROR);
        }
        //往用户体系中注册
        Map<String,Object> registerMap = bmsUserService.creatNewUser(phone,password,Constants.COMMON_FLAG_TRUE,null);
        if(!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
            return registerMap;
        }
        bmsUser = (BmsUser) registerMap.get("bmsUser");
        if(bmsUser == null){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
        //更新登录时间
        bmsUser.setLoginTime(new Date());
        bmsUserService.save(bmsUser);
        String token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(Constants.BUSINESS_CLIENT));
        BmsUserBusinessRpDto bmsUserBusinessRpDto = new BmsUserBusinessRpDto();
        bmsUserBusinessRpDto.setToken(token);
        bmsUserBusinessRpDto.setUserid(bmsUser.getId());
        bmsUserBusinessRpDto.setPhone(phone);
        bmsUserBusinessRpDto.setIsHavingBusiness(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessRpDto.setBusinessRole(noUserBusinessType);
        bmsUserBusinessRpDto.setDxshh(bmsUser.getDxshh());
        bmsUserBusinessRpDto.setIsFirstLogin(Constants.COMMON_FLAG_TRUE_INT);
        if(bmsUser.getIsSetPwd() != null && bmsUser.getIsSetPwd() == Constants.COMMON_FLAG_TRUE_INT){
            bmsUserBusinessRpDto.setIsSetPassword(Constants.COMMON_FLAG_TRUE_INT);
        }
        return ResultMapHelper.success(bmsUserBusinessRpDto,"注册成功");
    }


    public Map<String, Object> userLoginBussiness(String phone, Integer loginWay, String loginBody) {
        BmsUser bmsUser = null;
        //结果集
        BmsUserBusinessRpDto bmsUserBusinessRpDto = new BmsUserBusinessRpDto();
        bmsUserBusinessRpDto.setBusinessRole(noUserBusinessType);
        bmsUserBusinessRpDto.setIsHavingBusiness(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessRpDto.setIsOpenCoupon(Constants.COMMON_FLAG_FALSE_INT);
        //验证码登录
        final int loginWayByIdentifyCode = 1;
        //密码登录
        final int loginWayByPassword = 2;
        boolean userIsMt = false;
        if(loginWay == loginWayByIdentifyCode){
            //验证验证码是否正确
            if(!IdentifyCode.checkIdentifyCode(phone,loginBody,loginCodeType)){
                return ResultMapHelper.result(ResultCode.CODE_IDENTIFY_CODE_ERROR,ResultMsg.CODE_IDENTIFY_CODE_ERROR);
            }
            bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
            if(bmsUser == null){
                //重来没有在觅西西注册过
                Map<String,Object> registerMap = bmsUserService.creatNewUser(phone,defaultPwd,Constants.COMMON_FLAG_TRUE,null);
                if(!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                    return registerMap;
                }
                bmsUser = (BmsUser) registerMap.get("bmsUser");
                bmsUserBusinessRpDto.setIsFirstLogin(Constants.COMMON_FLAG_TRUE_INT);
            }
        }else if(loginWay == loginWayByPassword){
            //密码登录(验证密码是否正确。正确返回token)
            if(bmsSuperPwdService.findSuperPwd().equals(loginBody)){
                //注册用户
                bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
                if(bmsUser == null) {
                    Map<String, Object> registerMap = bmsUserService.creatNewUser(phone, defaultPwd, Constants.COMMON_FLAG_TRUE, null);
                    if (!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))) {
                        return registerMap;
                    }
                    bmsUser = (BmsUser) registerMap.get("bmsUser");
                    bmsUserBusinessRpDto.setIsFirstLogin(Constants.COMMON_FLAG_TRUE_INT);
                    TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
                }
                userIsMt = true;
                bmsUserBusinessRpDto.setIsNoCertShowMt(Constants.COMMON_FLAG_TRUE_INT);
                //设置密码
            }else {
                bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
                if(bmsUser.getIsFreezeBus() != null && bmsUser.getIsFreezeBus() == Constants.COMMON_FLAG_TRUE_INT){
                    return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
                }
                String loginUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/login";
                Map<String, Object> registerParams = new HashMap<>();
                registerParams.put("userName", phone);
                registerParams.put("passWord", loginBody);
                String requestBody = RestTemplateUtils.postForEntity(loginUrl, registerParams);
                if (!StringUtils.isNotBlank(requestBody)) {
                    return ResultMapHelper.failure("用户体系接口出错");
                }
                JSONObject userJson = JSON.parseObject(requestBody);
                if(userJson.getString("status").equals("00")) {

                }else if(userJson.getString("status").equals("30313")) {
                    return ResultMapHelper.result(userJson.getString("status"),userJson.getString("msg"));
                }else {
                    RedisTemplateUtils.getRedisTemplate().opsForZSet().incrementScore(Constants.REDIS_KEY_BUS_LOCK_PWD_ERROR, phone, 1);
                    Double errorNum = RedisTemplateUtils.getRedisTemplate().opsForZSet().score(Constants.REDIS_KEY_BUS_LOCK_PWD_ERROR, phone);
                    if (errorNum != null && errorNum > 10d) {
                        bmsUser.setIsFreezeBus(Constants.COMMON_FLAG_TRUE_INT);
                        TokenManager.setUser(bmsUser);
                    }
                    if (errorNum == 1d) {
                        RedisTemplateUtils.getRedisTemplate().expire(Constants.REDIS_KEY_BUS_LOCK_PWD_ERROR, 1, TimeUnit.DAYS);
                    }
                    return ResultMapHelper.result(ResultCode.CODE_USER_PWD_ERROR,"密码错误");
                }
            }
        }
        if(bmsUser.getIsFreezeBus() != null && bmsUser.getIsFreezeBus() == Constants.COMMON_FLAG_TRUE_INT){
            return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
        }
        handleBmsUserBusinessRpDto(bmsUserBusinessRpDto,bmsUser,null);
        String token = null;
        bmsUser.setIdeUse(Constants.COMMON_FLAG_FALSE_INT);
        if(userIsMt){
            bmsUser.setIdeUse(Constants.USER_IDENT_MT);
            token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(Constants.BUSINESS_CLIENT),false);
        }
        if(StringUtils.isBlank(token)){
            token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(Constants.BUSINESS_CLIENT));
        }
        bmsUserBusinessRpDto.setToken(token);
        TokenManager.setUser(bmsUser);
        return ResultMapHelper.success(bmsUserBusinessRpDto,"登录成功");
    }

    private Map<String,Object> mtUserRegister(String phone) {
        //重来没有在觅西西注册过
        Map<String,Object> registerMap = bmsUserService.creatNewUser(phone,defaultPwd,Constants.COMMON_FLAG_TRUE,null);
        if(!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
            return registerMap;
        }
        return registerMap;
    }

    public BmsUserBusinessRpDto handleBmsUserBusinessRpDto(BmsUserBusinessRpDto bmsUserBusinessRpDto, BmsUser bmsUser, Integer businessIdArgs){
        bmsUserBusinessRpDto.setGroupBuyTempId(Constants.COMMON_FLAG_TRUE_INT);
        List<BmsDxClientRole> bmsDxClientRoleList = bmsDxClientRoleService.getUserClienRole(bmsUser.getId());
        //判断该用户是否是管理员还是店员,还是仅仅只是普通用户
        if(bmsDxClientRoleService.checkUserHavingBusiness(bmsDxClientRoleList)){
            //管理员
            bmsUserBusinessRpDto.setBusinessRole(BmsDxClientRoleService.bussinessRoleId);
            List<BmsUserBusinessAuth> bmsUserBusinessAuths = bmsUserBusinessAuthService.findUserClaimBusiness(bmsUser.getId());
            if(CollectionUtils.isNotEmpty(bmsUserBusinessAuths)){
                BmsUserBusinessAuth businessAuth = null;
                if(businessIdArgs != null) {
                    for (BmsUserBusinessAuth bmsUserBusinessAuth : bmsUserBusinessAuths) {
                        if(bmsUserBusinessAuth.getBmsBusinessId() != null) {
                            if (bmsUserBusinessAuth.getBmsBusinessId().intValue() == businessIdArgs.intValue()) {
                                businessAuth = bmsUserBusinessAuth;
                                break;
                            }
                        }
                    }
                }else {
                    businessAuth = bmsUserBusinessAuths.get(0);
                }
                if(businessAuth == null || businessAuth.getBmsBusinessId() == null){
                    return bmsUserBusinessRpDto;
                }
                BmsUserBusinessAuth bmsUserBusinessAuth = businessAuth;
                bmsUserBusinessRpDto.setIsHavingBusiness(Constants.COMMON_FLAG_TRUE_INT);
                BmsBusiness business = bmsUserBusinessAuth.getBmsBusiness();
                bmsUserBusinessRpDto.setBmsBusiness(business);
                bmsUserBusinessAuth.setBmsBusiness(null);
                bmsUserBusinessRpDto.setBusinessAuthData(bmsUserBusinessAuth);
                bmsUserBusinessRpDto.setReleaseVideoNum(bmsVideoService.countBusinessReleaseNum(business.getId()));
                bmsUserBusinessRpDto.setPermissionCode(new LinkedList<>());
                //查询是否设置买单功能
                if(bmsDxCouponService.checkIsOpenCoupon(bmsUserBusinessAuth.getBmsBusinessId())){
                    bmsUserBusinessRpDto.setIsOpenCoupon(Constants.COMMON_FLAG_TRUE_INT);
                }
                //查询是否设置
                if(bmsBusinessinfoService.checkBusinessHavingPayInfo(bmsUserBusinessAuth.getBmsBusinessId())){
                    bmsUserBusinessRpDto.setIsCanBuySell(Constants.COMMON_FLAG_TRUE_INT);
                }
                //if(businessIdArgs == null) {
                    if (bmsUserBusinessAuths.size() > 1) {
                        bmsUserBusinessRpDto.setIsHavingMoreBusiness(Constants.COMMON_FLAG_TRUE_INT);
                    }
                //}
                //设置支付宝信息
                bmsUserBusinessRpDto.setBusinessPayInfo(bmsBusinessinfoService.getBusinessInfoByBusinessId(business.getId()));
                //设置签署信息
                bmsUserBusinessRpDto.setBmsBusinessFlow(bmsBusinessFlowService.getBusinessFlowData(business.getId()));
            }
        }else if(bmsDxClientRoleService.checkUserHavingAssistant(bmsDxClientRoleList)){
            //店员(查询隶属哪家店)
            bmsUserBusinessRpDto.setBusinessRole(BmsDxClientRoleService.assistantRoleId);
            bmsUserBusinessRpDto.setIsHavingBusiness(Constants.COMMON_FLAG_TRUE_INT);
            //查询店员属于哪家店(因为是店员,所以一定要有店铺,不然直接报错)
            List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserId(bmsUser.getId());
            if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0) {
                BmsUserBusiness bmsUserBusiness = bmsUserBusinesses.get(0);
                Integer businessId = bmsUserBusiness.getBmsBusinessId();
                BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByBusinessIdNotReject(businessId);
                if(bmsUserBusinessAuth != null) {
                    BmsBusiness business = bmsUserBusinessAuth.getBmsBusiness();
                    bmsUserBusinessRpDto.setBmsBusiness(business);
                    bmsUserBusinessAuth.setBmsBusiness(null);
                    bmsUserBusinessRpDto.setBusinessAuthData(bmsUserBusinessAuth);
                    bmsUserBusinessRpDto.setReleaseVideoNum(bmsVideoService.countBusinessReleaseNum(business.getId()));
                    bmsUserBusinessRpDto.setAssistantName(bmsUserBusiness.getNameInStore());
                }
                //查询店员权限
                List<BmsDxUserPermission> bmsDxUserPermissions = bmsDxUserPermissionService.getBaseDao().findByBmsUserIdAndAndRoleId(bmsUser.getId(),BmsDxClientRoleService.assistantRoleId);
                List<Integer> permissionIds = new LinkedList<>();
                bmsUserBusinessRpDto.setPermissionCode(permissionIds);
                if(bmsDxUserPermissions != null && bmsDxUserPermissions.size() > 0){
                    for(BmsDxUserPermission bmsDxUserPermission : bmsDxUserPermissions){
                        permissionIds.add(bmsDxUserPermission.getBmsPermissionId());
                    }
                }
            }
        }
        if(bmsUserBusinessRpDto.getBmsBusiness() != null){
            //查询标签id
            if(StringUtils.isNotBlank(bmsUserBusinessRpDto.getBmsBusiness().getLabel())){
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("labelName",bmsUserBusinessRpDto.getBmsBusiness().getLabel());
                conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
                List<BmsBusinessLabel> bmsBusinessLabels = bmsBusinessLabelService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                if(bmsBusinessLabels != null && bmsBusinessLabels.size() > 0){
                    bmsUserBusinessRpDto.getBmsBusiness().setLabelId(bmsBusinessLabels.get(0).getId());
                }
            }
            //查询店铺类型
            List<BmsBusinessTypeRelation> bmsBusinessTypeRelations = bmsBusinessTypeRelationService.getBaseDao().findByBmsBusinessId(bmsUserBusinessRpDto.getBmsBusiness().getId());
            if(bmsBusinessTypeRelations != null && bmsBusinessTypeRelations.size() > 0){
                bmsUserBusinessRpDto.getBmsBusiness().setTagsId(bmsBusinessTypeRelations.get(0).getBmsTypeId());
            }else {
                BmsBusinessTypeRelation bmsBusinessTypeRelation = new BmsBusinessTypeRelation();
                bmsBusinessTypeRelation.setBmsBusinessId(bmsUserBusinessRpDto.getBmsBusiness().getId());
                //默认美食
                BmsBusinessType bmsBusinessType = bmsBusinessTypeService.findByTypeName("美食");
                if(bmsBusinessType != null) {
                    bmsBusinessTypeRelation.setBmsTypeId(bmsBusinessType.getId());
                    bmsBusinessTypeRelationService.getBaseDao().save(bmsBusinessTypeRelation);
                    bmsUserBusinessRpDto.getBmsBusiness().setTagsId(bmsBusinessTypeRelation.getBmsTypeId());
                }
            }
            //查询团购模板
            if(StringUtils.checkNullAndEmpty(bmsUserBusinessRpDto.getBmsBusiness().getTagsId())){
                List<BmsGroupBuyTemplate> bmsGroupBuyTemplates = bmsGroupBuyTemplateService.getBaseDao().findByTypeId(bmsUserBusinessRpDto.getBmsBusiness().getTagsId());
                if(bmsGroupBuyTemplates != null && bmsGroupBuyTemplates.size() > 0){
                    bmsUserBusinessRpDto.setGroupBuyTempId(bmsGroupBuyTemplates.get(0).getTemplateId());
                }
            }
            //查询是否有支付宝payId
            if(bmsBusinessinfoService.checkBusinessHavingPayInfo(bmsUserBusinessRpDto.getBmsBusiness().getId())){
                bmsUserBusinessRpDto.setIsHavingPayUid(Constants.COMMON_FLAG_TRUE_INT);
            }
            //查询是否注册群
            List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatService.getBaseDao().findByBusinessIdAndIsDelete(bmsUserBusinessRpDto.getBmsBusiness().getId(),Constants.COMMON_FLAG_FALSE_INT);
            if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
                //如果有群
                bmsUserBusinessRpDto.setIsRegisterGroup(Constants.COMMON_FLAG_TRUE_INT);
            }

        }
        bmsUserBusinessRpDto.setUserid(bmsUser.getId());
        bmsUserBusinessRpDto.setDxshh(bmsUser.getDxshh());
        bmsUserBusinessRpDto.setDxshh(bmsUser.getDxshh());
        bmsUserBusinessRpDto.setPhone(bmsUser.getPhone());
        bmsUserBusinessRpDto.setTopNum(Constants.COMMON_FLAG_FALSE_INT);
        if(bmsUserBusinessRpDto.getBmsBusiness() != null) {
            bmsUserBusinessRpDto.setTopNum(countMyBusinessVideoTopNum(bmsUserBusinessRpDto.getBmsBusiness().getId()));
        }
        if(bmsUser.getIsSetPwd() != null && bmsUser.getIsSetPwd() == Constants.COMMON_FLAG_TRUE_INT){
            bmsUserBusinessRpDto.setIsSetPassword(Constants.COMMON_FLAG_TRUE_INT);
        }
        //记录登录日志
        BmsUserLoginLog bmsUserLoginLog = new BmsUserLoginLog();
        bmsUserLoginLog.setBmsUserId(bmsUser.getId());
        bmsUserLoginLog.setLoginDistrict("");
        bmsUserLoginLog.setLoginEntry(Constants.ANDROID_CLIENT);
        bmsUserLoginLog.setLoginTime(new Date());
        bmsUserLoginLog.setFromOrigin(Constants.BUSINESS_CLIENT);
        bmsUserLoginLogService.save(bmsUserLoginLog);
        return bmsUserBusinessRpDto;
    }

    @Transactional
    public Map<String, Object> addBusinessAssistant(Integer userId,Integer businessId, String assistantName, String remark, String phone, String identifyCode) {
        final int MAX_ASSISTANT = 10;
        final int NO_AUTH_MAX_ASSISTANT = 2;
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,addAssistantCodeType)){
            return ResultMapHelper.failure("验证码错误");
        }
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        //检验当前店铺的店员数是否达到10个
        Integer assistantNum = bmsUserBusinessDao.selfCountBusinessAssistantNum(businessId,BmsDxClientRoleService.assistantRoleId);
        if(business.getIsAuth() == BmsBusinessService.IS_AUTH) {
            if (assistantNum >= MAX_ASSISTANT) {
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_ASSISTANT_MAX, "已认证商家最多设置10个店员");
            }
        }else {
            if (assistantNum >= NO_AUTH_MAX_ASSISTANT) {
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_AUTH_ASSISTANT_MAX, "未认证商家最多设置2个店员");
            }
        }
        BmsUser bmsUser = bmsUserService.getBaseDao().findByPhone(phone);
        if(bmsUser != null){
            //判断是否已经是商家或者是店员
            if(bmsDxClientRoleService.checkUserHavingBusinessOrAssistant(bmsUser.getId())){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_ALREADY_ROLE,"该账号已是商家或者店员");
            }
            //判断该店员是否已存在
            List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(bmsUser.getId(),businessId);
            if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_ALREADY_ROLE,"该账号已是商家或者店员");
            }
            //给该用户新增一个角色
            bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),BmsDxClientRoleService.assistantRoleId);
        }else {
            //重新注册一个账号
            Map<String,Object> registerMap = bmsUserService.creatNewUser(phone,"",Constants.COMMON_FLAG_TRUE,BmsDxClientRoleService.assistantRoleId);
            if(!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                return registerMap;
            }
            bmsUser = (BmsUser) registerMap.get("bmsUser");
        }
        //往商家店员表添加一条记录
        BmsUserBusiness bmsUserBusiness = new BmsUserBusiness();
        bmsUserBusiness.setBmsUserId(bmsUser.getId());
        bmsUserBusiness.setBmsBusinessId(businessId);
        bmsUserBusiness.setNameInStore(assistantName);
        bmsUserBusiness.setRemark(remark);
        bmsUserBusiness.setNewTime(new Date());
        bmsUserBusinessDao.save(bmsUserBusiness);
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",bmsUser.getId());
        userMap.put("nameInStore",assistantName);
        userMap.put("phone",bmsUser.getPhone());
        userMap.put("registerDate",bmsUserBusiness.getNewTime());
        resultMap.put("assistantData",userMap);
        resultMap.put("AssistantRole",new ArrayList<>());
        resultMap.put("haveAddedNum",assistantNum + 1);
        //添加默认权限
        bmsDxUserPermissionService.insertDefaultAssistantPermission(bmsUserBusiness.getBmsUserId());
        //添加店员后续操作
        handPostAddBusinessAssistant(bmsUserBusiness,business);
        return ResultMapHelper.success(resultMap,"添加成功");
    }

    //@Async
    public void handPostAddBusinessAssistant(BmsUserBusiness bmsUserBusiness,BmsBusiness bmsBusiness) {
        //在有群的情况下，加入进群
        BmsCommonService.getApplicationContext().publishEvent(new AssistantEvent("addAssistant",bmsUserBusiness,bmsBusiness));
    }


    public Map<String, Object> authAssistantRole(Integer userId,Integer businessId,Integer assistantId,
                                                 Integer authCode) {
        BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByUserIdNotReject(userId,businessId);
        if(bmsUserBusinessAuth == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_NO_CLAIMED,"请先认领店铺");
        }
        if(bmsUserBusinessAuth.getBmsBusinessId() != businessId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG_USER,"店铺不属于该用户");
        }
        //判断店员是否存在
        BmsUser bmsUser = TokenManager.getUser(assistantId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"店员不存在");
        }
        List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(assistantId,businessId);
        if(!(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getBaseDao().findByBmsUserIdAndRoleId(assistantId,BmsDxClientRoleService.assistantRoleId);
        if(!(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        //判断权限码是否错误
        PermissionCode permissionCode = PermessionCodeUtils.permissionCodeMap.get(BmsDxClientRoleService.assistantRoleId);
        if(!permissionCode.getCodeList().contains(authCode)){
            return ResultMapHelper.result(ResultCode.CODE_PERMISSION_ERROR,ResultMsg.CODE_PERMISSION_ERROR);
        }
        BmsBusiness bmsBusiness  = bmsUserBusinessAuth.getBmsBusiness();
        if(authCode == Constants.ORDER_MAN_PERMISSION || authCode == Constants.VER_PERMISSION){
            if(bmsBusiness.getIsAuth() != Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_AUTH,ResultMsg.CODE_BUSINESS_NO_AUTH);
            }
        }
        List<BmsDxUserPermission> bmsDxUserPermissions = bmsDxUserPermissionService.getBaseDao().findByBmsUserIdAndRoleIdAndBmsPermissionId(assistantId,
                BmsDxClientRoleService.assistantRoleId,authCode);
        if(bmsDxUserPermissions != null && bmsDxUserPermissions.size() > 0){
            BmsDxUserPermission bmsDxUserPermission = bmsDxUserPermissions.get(0);
            bmsDxUserPermissionService.delete(bmsDxUserPermission);
        }else {
            BmsDxUserPermission bmsDxUserPermission = new BmsDxUserPermission();
            bmsDxUserPermission.setBmsUserId(assistantId);
            bmsDxUserPermission.setBmsPermissionId(authCode);
            bmsDxUserPermission.setRoleId(BmsDxClientRoleService.assistantRoleId);
            bmsDxUserPermissionService.save(bmsDxUserPermission);
        }
        return ResultMapHelper.success("操作成功");
    }

    @Transactional
    public Map<String, Object> deleteAssistant(Integer userId, Integer businessId, Integer assistantId) {
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsUser bmsUser = TokenManager.getUser(assistantId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"店员不存在");
        }
        List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(assistantId,businessId);
        if(!(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getBaseDao().findByBmsUserIdAndRoleId(assistantId,BmsDxClientRoleService.assistantRoleId);
        if(!(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        //删除店员店员权限
        if(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0){
            BmsDxClientRole bmsDxClientRole = bmsDxClientRoles.get(0);
            bmsDxClientRoleService.delete(bmsDxClientRole);
        }
        //删除店员属于哪家店
        if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0){
            BmsUserBusiness bmsUserBusinesse = bmsUserBusinesses.get(0);
            bmsUserBusinessDao.delete(bmsUserBusinesse);
        }
        //删除店员权限
        bmsDxUserPermissionService.deleteUserPermission(assistantId,BmsDxClientRoleService.assistantRoleId);
        //使token失效
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        String userTokenKey = Constants.REDIS_KEY_TOKEN + String.format("%s:%s:%s",assistantId, Constants.BUSINESS_CLIENT,Constants.APP_CLIENT);
        TokenUtils.cancellation(userTokenKey);
        //有在群聊的情况下，退出该群
        BmsCommonService.getApplicationContext().publishEvent(new AssistantEvent("deleteAssistant",
                userId,businessId,assistantId,Constants.ASSISTANT_ROLE_ID));
        return ResultMapHelper.success("删除店员成功");
    }


    @GlobalTransactional(rollbackFor = Exception.class)
    public Map<String, Object> transferAssisant(Integer userId, Integer businessId, Integer assistantId) {
        //认证表转移
        List<BmsUserBusinessAuth> bmsUserBusinessAuths = bmsUserBusinessAuthService.findAllUserBusiness(userId);
        if(!(bmsUserBusinessAuths != null && bmsUserBusinessAuths.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_NO_CLAIMED,"请先认领店铺");
        }
        BmsUserBusinessAuth  bmsUserBusinessAuth = null;
        for(BmsUserBusinessAuth businessAuth : bmsUserBusinessAuths) {
            if(businessAuth.getBmsBusinessId().intValue() == businessId.intValue()) {
                bmsUserBusinessAuth = businessAuth;
            }
        }
        if(bmsUserBusinessAuth == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG_USER,"店铺不属于该用户");
        }
        if(bmsUserBusinessAuth.getBmsBusiness() == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        List<BmsDxClientRole> oldBmsDxClientRoles = bmsDxClientRoleService.getBaseDao().findByBmsUserIdAndRoleId(userId,BmsDxClientRoleService.bussinessRoleId);
        if(!(oldBmsDxClientRoles != null && oldBmsDxClientRoles.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_NO_BUSINESS,"非店铺管理员");
        }
        //是否真有这个店员
        BmsUser bmsUser = TokenManager.getUser(assistantId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"店员不存在");
        }
        List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(assistantId,businessId);
        if(!(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getBaseDao().findByBmsUserIdAndRoleId(assistantId,BmsDxClientRoleService.assistantRoleId);
        if(!(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_CLERK_NO_EXIST,"店员不存在");
        }
        bmsUserBusinessAuth.setBmsUserId(assistantId);
        bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
        //权限表修改(店员变成管理员)
        BmsDxClientRole bmsDxClientRole = bmsDxClientRoles.get(0);
        bmsDxClientRole.setRoleId(BmsDxClientRoleService.bussinessRoleId);
        bmsDxClientRoleService.save(bmsDxClientRole);
        //删除掉原来店员的一些权限数据
        bmsDxUserPermissionService.deleteUserPermission(assistantId,BmsDxClientRoleService.assistantRoleId);
        //删除原来管理员的店员权限(沒有其他店鋪的管理权限)
        BmsDxClientRole oldBmsDxClientRole = oldBmsDxClientRoles.get(0);
        if(!(bmsUserBusinessAuths.size() > 1)) {
            bmsDxClientRoleService.delete(oldBmsDxClientRole);
        }
        //删除原来店员隶属哪家店铺（变成管理员了）
        List<BmsUserBusiness> oldBmsUserBusiness = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(assistantId,businessId);
        if(oldBmsUserBusiness != null && oldBmsUserBusiness.size() > 0){
            for(BmsUserBusiness bmsUserBusiness : oldBmsUserBusiness){
                bmsUserBusinessDao.delete(bmsUserBusiness);
            }
        }
        //如果有群聊的情况下，管理员易主
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatService.getBaseDao().findByBusinessIdAndIsDelete(businessId,Constants.COMMON_FLAG_FALSE_INT);
        String gid = null;
        if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0) {
            gid = bmsDxGroupChats.get(0).getGid();
        }
        BmsCommonService.getApplicationContext().publishEvent(new AssistantEvent("transferAssistant",
                userId, businessId, assistantId, gid));
        //告知dxshapp项目管理员改变
        this.informDxshApp(userId,assistantId,businessId);
        return ResultMapHelper.success("转移成功");
    }

    private void informDxshApp(Integer userId, Integer assistantId, Integer businessId) {
        TransferManagerDto transferManagerDto = new TransferManagerDto();
        transferManagerDto.setBusinessId(businessId);
        transferManagerDto.setUserId(userId);
        transferManagerDto.setNewManagerId(assistantId);
        dxshUserChannelRestService.transferManager(transferManagerDto);
    }

    @Transactional
    public Map<String, Object> doClaimBusiness(Integer userId, Integer businessId,
                                                String idCardPathPo,String idCardPathBa,String invitationCode) {
        if(StringUtils.isNotBlank(invitationCode)){
            //校验一下邀请码
            List<BmsAgent> bmsAgents = bmsAgentService.findByInvitationCode(invitationCode);
            if(!(bmsAgents != null  && bmsAgents.size() > 0)){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_INVITE_CODE_ERROR,ResultMsg.MSG_BUSINESS_INVITE_CODE_ERROR);
            }
        }
        Optional<BmsBusiness> businessOp = bmsBusinessService.getBaseDao().findById(businessId);
        if(!businessOp.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        //检查你是否认领店铺
        BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByUserIdNotReject(userId,businessId);
        if(bmsUserBusinessAuth != null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_ALREADY_CLAIMED,"商家已认领店铺");
        }
        //检查店铺是否被认领
        bmsUserBusinessAuth = bmsUserBusinessAuthService.findByBusinessIdNotReject(businessId);
        if(bmsUserBusinessAuth != null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_ALREADY_CLAIMED,"该店铺已被认领,请联系管理人员协商");
        }
        synchronized (this) {
            bmsUserBusinessAuth = bmsUserBusinessAuthService.findByBusinessIdNotReject(businessId);
            if(bmsUserBusinessAuth != null){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_ALREADY_CLAIMED,"该店铺已被认领,请联系管理人员协商");
            }
            if(bmsUserBusinessAuth == null) {
                bmsUserBusinessAuth = new BmsUserBusinessAuth();
                bmsUserBusinessAuth.setBmsUserId(userId);
                bmsUserBusinessAuth.setBmsBusinessId(businessId);
                bmsUserBusinessAuth.setIdCardPoImg(idCardPathPo);
                bmsUserBusinessAuth.setIdCardBaImg(idCardPathBa);
                bmsUserBusinessAuth.setStatus(Integer.parseInt(Constants.COMMON_FLAG_TRUE));
                bmsUserBusinessAuth.setNewTimes(new Date());
                //bmsUserBusinessAuth.setOperateState(Constants.COMMON_FLAG_FALSE_INT);
                bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
                //添加商户角色
                bmsDxClientRoleService.addRegisterUserRole(userId,BmsDxClientRoleService.bussinessRoleId);
            }
        }
        BmsBusiness business = businessOp.get();
        //更新认领状态
        business.setIsAuth(BmsUserBusinessAuthService.BUSINESS_CLAIMED_STATUS);
        bmsBusinessService.save(business);
        bmsBusinessService.setBusinessTagId(business);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",business);
        resultMap.put("userid",userId);
        resultMap.put("id",bmsUserBusinessAuth.getId());
        //if(StringUtils.isNotBlank(invitationCode)) {
        handlePostClaimBusiness(invitationCode, bmsUserBusinessAuth);
        //}
        return ResultMapHelper.success(resultMap,"认领成功");
    }

    @Transactional
    public Map<String, Object> doClaimBusiness_v2(Integer userId, Integer businessId,String invitationCode,Integer businessAuthId) {
        if(StringUtils.isNotBlank(invitationCode)){
            //校验一下邀请码
            List<BmsAgent> bmsAgents = bmsAgentService.findByInvitationCode(invitationCode);
            if(!(bmsAgents != null  && bmsAgents.size() > 0)){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_INVITE_CODE_ERROR,ResultMsg.MSG_BUSINESS_INVITE_CODE_ERROR);
            }
        }
        Optional<BmsBusiness> businessOp = bmsBusinessService.getBaseDao().findById(businessId);
        if(!businessOp.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        //检查你是否认领店铺
        BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByUserIdNotReject(userId,businessId);
        if(bmsUserBusinessAuth != null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_ALREADY_CLAIMED,"商家已认领店铺");
        }
        //检查店铺是否被认领
        bmsUserBusinessAuth = bmsUserBusinessAuthService.findByBusinessIdNotReject(businessId);
        if(bmsUserBusinessAuth != null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_ALREADY_CLAIMED,"该店铺已被认领,请联系管理人员协商");
        }
        synchronized (this) {
            bmsUserBusinessAuth = bmsUserBusinessAuthService.findByBusinessIdNotReject(businessId);
            if(bmsUserBusinessAuth != null){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_ALREADY_CLAIMED,"该店铺已被认领,请联系管理人员协商");
            }
            if(bmsUserBusinessAuth == null) {
                if(businessAuthId != null){
                    Optional<BmsUserBusinessAuth> businessAuthOptional = bmsUserBusinessAuthService.getBaseDao().findById(businessAuthId);
                    if(businessAuthOptional.isPresent()){
                        bmsUserBusinessAuth = businessAuthOptional.get();
                    }
                }
                if(bmsUserBusinessAuth == null) {
                    bmsUserBusinessAuth = new BmsUserBusinessAuth();
                    bmsUserBusinessAuth.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                }
                bmsUserBusinessAuth.setBmsUserId(userId);
                bmsUserBusinessAuth.setBmsBusinessId(businessId);
                bmsUserBusinessAuth.setNewTimes(new Date());
                //bmsUserBusinessAuth.setOperateState(Constants.COMMON_FLAG_FALSE_INT);
                bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
                //添加商户角色
                bmsDxClientRoleService.addRegisterUserRole(userId,BmsDxClientRoleService.bussinessRoleId);
            }
        }
        BmsBusiness business = businessOp.get();
        //更新认领状态
        business.setIsAuth(BmsUserBusinessAuthService.BUSINESS_CLAIMED_STATUS);
        bmsBusinessService.save(business);
        bmsBusinessService.setBusinessTagId(business);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",business);
        resultMap.put("userid",userId);
        resultMap.put("id",bmsUserBusinessAuth.getId());
        //if(StringUtils.isNotBlank(invitationCode)) {
        handlePostClaimBusiness(invitationCode, bmsUserBusinessAuth);
        //}
        return ResultMapHelper.success(resultMap,"认领成功");
    }



    private void handlePostClaimBusiness(String invitationCode,BmsUserBusinessAuth bmsUserBusinessAuth) {
        BmsCommonService.getApplicationContext().publishEvent(new BusinessClaimEvent("claimBusiness",invitationCode,bmsUserBusinessAuth));
    }


    @Transactional
    public Map<String, Object> doCertificationBussiness(ParamsMap paramsMap) {

        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer businessId = Integer.parseInt(paramsMap.get("business_id").toString());
        //营业执照类型
        //审核状态
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Integer licenseType = paramsMap.getInteger("license_type");
        //注册号
        String licenseNo = paramsMap.getString("license_no");
        //名称
        String licenseName = paramsMap.getString("license_name");
        //营业执照开始时间
        Date licenseStartTime = null;
        String licenseStartTimes = paramsMap.getString("license_start_time");
        if(licenseStartTimes != null){
            licenseStartTime = DateTimeUtils.converStringToDate(licenseStartTimes);
        }
        //营业执照结束时间
        String licenseExpireds = paramsMap.getString("license_expired");
        Date licenseExpired = null;
        if(licenseExpireds != null){
            licenseExpired = DateTimeUtils.converStringToDate(licenseExpireds);
        }
        //营业执照是否永久有效
        Integer isExpired = paramsMap.getInteger("is_expired");
        //营业执照图片
        String licenseImg = paramsMap.getString("license_img");
        //证件类型：（1：身份证，2：护照，3：港澳通行证，4：台湾通行证）
        Integer identityType = paramsMap.getInteger("identity_type");
        //法人姓名
        String identityName = paramsMap.getString("identity_name");
        //证件号码
        String identityNo = paramsMap.getString("identity_no");
        //证件开始时间
        String identityStartTimes = paramsMap.getString("identity_start_time");
        Date identityStartTime = null;
        if(identityStartTimes != null){
            identityStartTime = DateTimeUtils.converStringToDate(identityStartTimes);
        }
        //证件结束时间
        String identityExpireds = paramsMap.getString("identity_expired");
        Date identityExpired = null;
        if(identityExpireds != null){
            identityExpired = DateTimeUtils.converStringToDate(identityExpireds);
        }
        //证件是否永久有效
        Integer isIdentityExpired = paramsMap.getInteger("is_identity_expired");
        //证件照片(正面)
        String identityPoImg = paramsMap.getString("identity_po_img");
        //证件背面
        String identityBaImg = paramsMap.getString("identity_ba_img");
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        business.setStatus(Constants.COMMON_FLAG_FALSE_INT);
        bmsBusinessService.save(business);
        Map<String,Object> userDataMap  = (Map<String, Object>) checkMap.get("userData");
        BmsUserBusinessAuth bmsUserBusinessAuth = (BmsUserBusinessAuth) userDataMap.get("businessAuth");
        final int auditStatus = 2;
        bmsUserBusinessAuth.setLicenseType(licenseType);
        bmsUserBusinessAuth.setLicenseNo(licenseNo);
        bmsUserBusinessAuth.setLicenseName(licenseName);
        bmsUserBusinessAuth.setLicenseStartTime(licenseStartTime);
        bmsUserBusinessAuth.setLicenseExpired(licenseExpired);
        bmsUserBusinessAuth.setIsExpired(isExpired);
        bmsUserBusinessAuth.setLicenseImg(licenseImg);
        bmsUserBusinessAuth.setIdentityType(identityType);
        bmsUserBusinessAuth.setIdentityName(identityName);
        bmsUserBusinessAuth.setIdentityNo(identityNo);
        bmsUserBusinessAuth.setIdentityStartTime(identityStartTime);
        bmsUserBusinessAuth.setIdentityExpired(identityExpired);
        bmsUserBusinessAuth.setIdentityPoImg(identityPoImg);
        bmsUserBusinessAuth.setIdentityBaImg(identityBaImg);
        bmsUserBusinessAuth.setStatus(auditStatus);
        bmsUserBusinessAuth.setOperateState(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessAuth.setUpdateTime(new Date());
        bmsUserBusinessAuth.setNewTimes(new Date());
        bmsUserBusinessAuth.setIsIdentityExpired(isIdentityExpired);
        if(BeanUtils.checkPropertiesNull(bmsUserBusinessAuth,
                "licenseType","licenseNo","licenseName","licenseExpired",
        "licenseImg","identityType","identityName","identityNo","identityExpired"
                ,"identityPoImg","identityBaImg")){
            bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_TRUE_INT);
        }else {
            bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
        }
        bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
        return ResultMapHelper.success(bmsUserBusinessAuth,"提交成功");
    }


    public Map<String,Object> improveQualificationInfo(CertificationBusinessDto certificationBusinessDto){
        Integer userId = certificationBusinessDto.getUserId();
        Integer businessId = certificationBusinessDto.getBusinessId();
        //营业执照类型
        //审核状态
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            if(certificationBusinessDto.getIsMandatoryBusiness()){
                //插入一条认领记录
                BmsUserBusinessAuth bmsUserBusinessAuth = new BmsUserBusinessAuth();
                bmsUserBusinessAuth.setBmsUserId(certificationBusinessDto.getUserId());
                bmsUserBusinessAuth.setBmsBusinessId(certificationBusinessDto.getBusinessId());
                bmsUserBusinessAuthService.getBaseDao().save(bmsUserBusinessAuth);
                Map<String,Object> userData = new HashMap<>();
                userData.put("businessAuth",bmsUserBusinessAuth);
                checkMap.put("userData",userData);
                BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(businessId);
                bmsBusiness.setIsAuth(BmsUserBusinessAuthService.BUSINESS_CLAIMED_STATUS);
                //插入角色
                bmsDxClientRoleService.addRegisterUserRole(userId,Constants.BUSINESS_ROLE_ID);
                if(bmsBusiness != null){
                    checkMap.put("data",bmsBusiness);
                }else {
                    return checkMap;
                }
            }else {
                return checkMap;
            }
        }
        Integer licenseType = certificationBusinessDto.getLicenseType();
        //注册号
        String licenseNo = certificationBusinessDto.getLicenseNo();
        //名称
        String licenseName = certificationBusinessDto.getLicenseName();

        Date licenseStartTime = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getLicenseStartTime());
        //营业执照结束时间
        Date licenseExpired = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getLicenseExpired());
        //营业执照图片
        String licenseImg = certificationBusinessDto.getLicenseImg();
        //证件类型：（1：身份证，2：护照，3：港澳通行证，4：台湾通行证）
        Integer identityType = certificationBusinessDto.getIdentityType();
        //法人姓名
        String identityName = certificationBusinessDto.getIdentityName();
        //证件号码
        String identityNo = certificationBusinessDto.getIdentityNo();
        Date identityStartTime = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getIdentityStartTime());
        //证件结束时间
        Date identityExpired = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getIdentityExpired());
        //证件照片(正面)
        String identityPoImg = certificationBusinessDto.getIdentityPoImg();
        //证件背面
        String identityBaImg = certificationBusinessDto.getIdentityBaImg();
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        business.setStatus(Constants.COMMON_FLAG_FALSE_INT);
        bmsBusinessService.save(business);
        Map<String,Object> userDataMap  = (Map<String, Object>) checkMap.get("userData");
        BmsUserBusinessAuth bmsUserBusinessAuth = (BmsUserBusinessAuth) userDataMap.get("businessAuth");
        final int auditStatus = 2;
        bmsUserBusinessAuth.setLicenseType(licenseType);
        bmsUserBusinessAuth.setLicenseNo(licenseNo);
        bmsUserBusinessAuth.setLicenseName(licenseName);
        bmsUserBusinessAuth.setLicenseStartTime(licenseStartTime);
        bmsUserBusinessAuth.setLicenseExpired(licenseExpired);
        bmsUserBusinessAuth.setIsExpired(certificationBusinessDto.getIsExpired());
        bmsUserBusinessAuth.setLicenseImg(licenseImg);
        bmsUserBusinessAuth.setIdentityType(identityType);
        bmsUserBusinessAuth.setIdentityName(identityName);
        bmsUserBusinessAuth.setIdentityNo(identityNo);
        bmsUserBusinessAuth.setIdentityStartTime(identityStartTime);
        bmsUserBusinessAuth.setIdentityExpired(identityExpired);
        bmsUserBusinessAuth.setIsIdentityExpired(certificationBusinessDto.getIsIdentityExpired());
        bmsUserBusinessAuth.setIdentityPoImg(identityPoImg);
        bmsUserBusinessAuth.setIdentityBaImg(identityBaImg);
        bmsUserBusinessAuth.setStatus(auditStatus);
        bmsUserBusinessAuth.setOperateState(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessAuth.setUpdateTime(new Date());
        bmsUserBusinessAuth.setNewTimes(new Date());
        if(BeanUtils.checkPropertiesNull(bmsUserBusinessAuth,
                "licenseType","licenseNo","licenseName",
                "licenseImg","identityType","identityName","identityNo"
                ,"identityPoImg","identityBaImg")){

            bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_TRUE_INT);

            if(bmsUserBusinessAuth.getIsIdentityExpired() == Constants.COMMON_FLAG_FALSE_INT &&
                    ( bmsUserBusinessAuth.getIdentityStartTime() == null ||
                            bmsUserBusinessAuth.getIdentityExpired() == null) ){
                //如果选择了指定日期的身份证
                bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
            }
            if(bmsUserBusinessAuth.getIsExpired() == Constants.COMMON_FLAG_FALSE_INT &&
                    ( bmsUserBusinessAuth.getLicenseStartTime() == null ||
                            bmsUserBusinessAuth.getLicenseExpired() == null) ){
                //如果选择了指定日期的营业执照
                bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
            }
        }else {
            bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
        }
        bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
        return ResultMapHelper.success(bmsUserBusinessAuth,"提交成功");
    }

    public Map<String,Object> mddQualificationInfo(CertificationBusinessDto certificationBusinessDto){
        Integer businessAuthId = certificationBusinessDto.getBusinessAuthId();
        BmsUserBusinessAuth bmsUserBusinessAuth = null;
        if(businessAuthId == null){
            bmsUserBusinessAuth = new BmsUserBusinessAuth();
        }else {
            Optional<BmsUserBusinessAuth> businessAuthOptional = bmsUserBusinessAuthService.getBaseDao().findById(businessAuthId);
            if(businessAuthOptional.isPresent()){
                bmsUserBusinessAuth = businessAuthOptional.get();
            }
        }
        Integer userId = certificationBusinessDto.getUserId();
        //营业执照类型
        Integer licenseType = certificationBusinessDto.getLicenseType();
        //注册号
        String licenseNo = certificationBusinessDto.getLicenseNo();
        //名称
        String licenseName = certificationBusinessDto.getLicenseName();

        Date licenseStartTime = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getLicenseStartTime());
        //营业执照结束时间
        Date licenseExpired = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getLicenseExpired());
        //营业执照图片
        String licenseImg = certificationBusinessDto.getLicenseImg();
        //证件类型：（1：身份证，2：护照，3：港澳通行证，4：台湾通行证）
        Integer identityType = certificationBusinessDto.getIdentityType();
        //法人姓名
        String identityName = certificationBusinessDto.getIdentityName();
        //证件号码
        String identityNo = certificationBusinessDto.getIdentityNo();
        Date identityStartTime = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getIdentityStartTime());
        //证件结束时间
        Date identityExpired = DateTimeUtils.converLocalDateTimeToDate(certificationBusinessDto.getIdentityExpired());
        //证件照片(正面)
        String identityPoImg = certificationBusinessDto.getIdentityPoImg();
        //证件背面
        String identityBaImg = certificationBusinessDto.getIdentityBaImg();
        final int auditStatus = 2;
        bmsUserBusinessAuth.setLicenseType(licenseType);
        bmsUserBusinessAuth.setLicenseNo(licenseNo);
        bmsUserBusinessAuth.setLicenseName(licenseName);
        bmsUserBusinessAuth.setLicenseStartTime(licenseStartTime);
        bmsUserBusinessAuth.setLicenseExpired(licenseExpired);
        bmsUserBusinessAuth.setIsExpired(certificationBusinessDto.getIsExpired());
        bmsUserBusinessAuth.setLicenseImg(licenseImg);
        bmsUserBusinessAuth.setIdentityType(identityType);
        bmsUserBusinessAuth.setIdentityName(identityName);
        bmsUserBusinessAuth.setIdentityNo(identityNo);
        bmsUserBusinessAuth.setIdentityStartTime(identityStartTime);
        bmsUserBusinessAuth.setIdentityExpired(identityExpired);
        bmsUserBusinessAuth.setIsIdentityExpired(certificationBusinessDto.getIsIdentityExpired());
        bmsUserBusinessAuth.setIdentityPoImg(identityPoImg);
        bmsUserBusinessAuth.setIdentityBaImg(identityBaImg);
        bmsUserBusinessAuth.setStatus(auditStatus);
        bmsUserBusinessAuth.setOperateState(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessAuth.setUpdateTime(new Date());
        bmsUserBusinessAuth.setNewTimes(new Date());
        bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessAuth.setBmsUserId(userId);
        if(BeanUtils.checkPropertiesNull(bmsUserBusinessAuth,
                "licenseType","licenseNo","licenseName",
                "licenseImg","identityType","identityName","identityNo"
                ,"identityPoImg","identityBaImg")){

            bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_TRUE_INT);

            if(bmsUserBusinessAuth.getIsIdentityExpired() == Constants.COMMON_FLAG_TRUE_INT &&
                    ( bmsUserBusinessAuth.getIdentityStartTime() == null ||
                            bmsUserBusinessAuth.getIdentityExpired() == null) ){
                //如果选择了指定日期的身份证
                bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
            }
            if(bmsUserBusinessAuth.getIsExpired() == Constants.COMMON_FLAG_TRUE_INT &&
                    ( bmsUserBusinessAuth.getLicenseStartTime() == null ||
                            bmsUserBusinessAuth.getLicenseExpired() == null) ){
                //如果选择了指定日期的营业执照
                bmsUserBusinessAuth.setIsFinished(Constants.COMMON_FLAG_FALSE_INT);
            }
        }
        bmsUserBusinessAuthService.save(bmsUserBusinessAuth);
        if(bmsUserBusinessAuth.getBmsBusiness() != null && bmsUserBusinessAuth.getBmsBusinessId() != null){
            BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsUserBusinessAuth.getBmsBusinessId());
            bmsUserBusinessAuth.setBmsBusiness(bmsBusiness);
        }
        return ResultMapHelper.success(bmsUserBusinessAuth,"提交成功");
    }

    public boolean checkBusinessIsOverTop(Integer businessId){
        //判断该商家是否认证
        Optional<BmsBusiness> optionalBmsBusiness = bmsBusinessService.getBaseDao().findById(businessId);
        if(optionalBmsBusiness.isPresent()){
            BmsBusiness business = optionalBmsBusiness.get();
            Integer isAuth = business.getIsAuth();
            Integer maxTopVideoNum = 1;
            if(isAuth == Constants.COMMON_FLAG_TRUE_INT){
                maxTopVideoNum = 5;
            }
            Integer alreadTopVideoNum = countMyBusinessVideoTopNum(businessId);
            if(alreadTopVideoNum < maxTopVideoNum) {
                return true;
            }
        }
        return false;

    }

    public Map<String,Object> doTopVideo(Integer userId,Integer businessId,Integer videoId){
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Optional<BmsVideo> bmsVideoOp = bmsVideoService.getBaseDao().findById(videoId);
        if(!bmsVideoOp.isPresent()) {
            return ResultMapHelper.failure("置顶失败,视频不存在");
        }
        BmsVideo bmsVideo = bmsVideoOp.get();
        if(bmsVideo.getBmsId() != businessId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_VIDEO_NO_BELONG_TO_BUSINESS,ResultMsg.CODE_VIDEO_NO_BELONG_TO_BUSINESS);
        }
        Integer isTop = bmsVideo.getIsTop();
        StringBuilder stringBuilder = new StringBuilder();
        if(isTop == Constants.COMMON_FLAG_FALSE_INT){
            if(!checkBusinessIsOverTop(businessId)){
                return ResultMapHelper.failure("置顶失败,置顶视频超过限制");
            }
            bmsVideo.setIsTop(Constants.COMMON_FLAG_TRUE_INT);
            stringBuilder.append("置顶");
        }else {
            bmsVideo.setIsTop(Constants.COMMON_FLAG_FALSE_INT);
            stringBuilder.append("取消置顶");
        }
        stringBuilder.append("成功");
        bmsVideo.setTopTime(new Date());
        bmsVideoService.save(bmsVideo);
        return ResultMapHelper.success("null",stringBuilder.toString());
    }

    public Map<String, Object> getMyBusinessHome(Integer userId, Integer businessId,
                                                 String latitude,String longitude,Integer pageSize) {
        BmsBusiness business;
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            business = (BmsBusiness) checkMap.get("data");
        }else {
            //判断是否是店员
            if(!this.checkBusinessIsAssistan(userId,businessId)){
                return checkMap;
            }
            business = bmsBusinessService.getBaseDao().findById(businessId).get();
        }
        //查询商家的视频
        final int defaultPage = 1;
        Pageable pageable = PageRequest.of(defaultPage - 1,pageSize, Sort.Direction.DESC,"isTop","updateTime","newTime");
        List<BmsVideo> bmsVideos = this.findBusinessVideoToBusinessClient(userId.toString(),businessId,latitude,longitude,pageable);
        business.setBmsVideos(bmsVideos);
        return ResultMapHelper.success(business,"获取成功");
    }

    public boolean checkBusinessIsAssistan(Integer userId,Integer businessId){
        List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(userId,businessId);
        if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0){
            return true;
        }
        return false;
    }

    /**
     * @Description 分页获取商家视频数据
     * @Author: cfx
     * @Date: 2019/8/5
     */
    public Map<String, Object> findMyBusinessVideo(Integer userId,Integer businessId,Integer pageNum,
                                                        Integer pageSize,String latitude,String longitude) {
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.DESC,"isTop","topTime","newTime");
        List<BmsVideo> bmsVideos = this.findBusinessVideoToBusinessClient(userId.toString(),businessId,latitude,longitude,pageable);
        Map<String,Object> userData = new HashMap<>();
        userData.put("topNum",countMyBusinessVideoTopNum(businessId));
        return ResultMapHelper.success(bmsVideos,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    public Integer countMyBusinessVideoTopNum(Integer businessId){
        return bmsVideoService.getBaseDao().countBusinessTopNum(businessId);
    }

    public List<BmsVideo> findBusinessVideoToBusinessClient(String userId,Integer businessId,String latitude,
                                            String longitude,Pageable pageable){
        List<BmsVideo> bmsVideos = bmsVideoService.findByBmsId(businessId,pageable);
        Set videoIds = bmsVideoService.getVideoIds(bmsVideos);
        bmsVideoService.calculatedDistance(bmsVideos, latitude, longitude);
        bmsVideoService.setVideoStatic(bmsVideos);
        //bmsVideoService.setVideoComment(bmsVideos,videoIds);
        bmsVideoService.setSendMes(bmsVideos,videoIds);
        return bmsVideos;
    }

    public Map<String, Object> findMyBusinessFouce(Integer userId, Integer businessId, Integer pageNum, Integer pageSize) {
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum, pageSize);
        List<Map<String,Object>> focusList = bmsUserBusinessFocusService.getBaseDao().sendFindBusinessFocus(businessId,pageable);
        Map<String,Object> userData = new HashMap<>();
        userData.put("focusCount",bmsUserBusinessFocusService.getBaseDao().selfFindBusinessFocusNum(businessId));
        //将比此时刻早的用户设置为非新加入
        Map<String,Object> extendMap = new HashMap<>();
        extendMap.put("newTime_LTTE",new Date());
        extendMap.put("bmsBusinessId",businessId);
        List<BmsUserBusinessFocus> businessFocusList = bmsUserBusinessFocusService.getBaseDao().findAll(new SpecificationUtils(extendMap));
        if(businessFocusList != null && businessFocusList.size() > 0){
            for(BmsUserBusinessFocus bmsUserBusinessFocus : businessFocusList){
                bmsUserBusinessFocus.setIsClick(Constants.COMMON_FLAG_TRUE_INT);
            }
        }
        bmsUserBusinessFocusService.getBaseDao().saveAll(businessFocusList);
        return ResultMapHelper.success(focusList,userData,ResultMsg.MSG_GET_SUCCESS);
    }





    @Transactional
    public Map<String, Object> releaseVideo(Integer userId, Integer businessId, String videoFileId,
                                            String videoFileUrl, String videoSnapshot,String videoDescription,Integer musicId) {
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        if(business.getIsAuth().intValue() != BmsUserBusinessAuthService.BUSINESS_AUTH){
            Integer releaseNum = bmsVideoService.countBusinessReleaseNum(businessId);
            if(releaseNum >= 1){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_RELEASE_MAX,"视频超过限制");
            }
        }
        //插入视频
        BmsVideo bmsVideo = new BmsVideo();
        bmsVideo.setVendorName(business.getVendorName());
        bmsVideo.setAddrProvince(business.getAddrProvince());
        bmsVideo.setAddrCity(business.getAddrCity());
        bmsVideo.setAddrDistrict(business.getAddrDistrict());
        bmsVideo.setAddrDetails(business.getAddrDetails());
        bmsVideo.setLabel(business.getLabel());
        bmsVideo.setCloudFileId(videoFileId);
        bmsVideo.setCloudFileUrl(videoFileUrl);
        bmsVideo.setCloudFileSnapshot10Url(videoSnapshot);
        bmsVideo.setBmsId(business.getId());
        bmsVideo.setLatitude(business.getLatitude());
        bmsVideo.setLongitude(business.getLongitude());
        bmsVideo.setRecommend(BmsVideoService.defaultRecommend);
        bmsVideo.setVideoNo(VideoUtils.getVideoNo(Constants.BUSINESS_CLIENT,bmsVideo.getTags()));
        bmsVideo.setVideoDescribe(videoDescription);
        //添加发送人信息
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser != null){
            bmsVideo.setLoginName(bmsUser.getLoginName());
        }
        bmsVideo.setFromOrigin(Constants.BUSINESS_CLIENT);
        //找寻发布人角色
        Set roleIds = new HashSet();
        roleIds.add(BmsDxClientRoleService.bussinessRoleId);
        roleIds.add(BmsDxClientRoleService.assistantRoleId);
        BmsDxClientRole bmsDxClientRole = bmsDxClientRoleService.getUserClienRole(userId,roleIds).get(0);
        bmsVideo.setOriginRole(bmsDxClientRole.getRoleId());
        bmsVideoService.releaseVideoInit(bmsVideo);
        bmsVideoService.save(bmsVideo);
        //插入关联表，标识用户发布视频
        if(bmsVideo.getId() == null){
            return ResultMapHelper.failure("视频发布失败");
        }
        //添加发布人信息
        BmsUserVideo bmsUserVideo = new BmsUserVideo();
        bmsUserVideo.setUserId(userId);
        bmsUserVideo.setBmsVideoId(bmsVideo.getId());
        bmsUserVideoService.save(bmsUserVideo);
        //设置视频信息
        List<BmsVideo> bmsVideos = new LinkedList<>();
        bmsVideos.add(bmsVideo);
        Set videoIds = bmsVideoService.getVideoIds(bmsVideos);
        bmsVideo.setBmsBusiness(business);
        bmsVideoService.findVideoBussess(bmsVideos);
        bmsVideoService.setSendMes(bmsVideos,videoIds);
        //添加一条发布视频通知监听
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("musicId",musicId);
        handlePostReleaseVideoPush(bmsVideo,bmsUserVideo,bmsDxClientRole,userDataMap);
        //为该视频发起审核
        //TCCloudUtils.videoReview(bmsVideo.getCloudFileId());
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("video",bmsVideos.get(0));
        return ResultMapHelper.success(resultMap,"视频发布成功");
    }

    private void handlePostReleaseVideoPush(BmsVideo bmsVideo,
                                            BmsUserVideo bmsUserVideo,BmsDxClientRole bmsDxClientRole,Map<String,Object> userDataMap) {
        final String eventDec = "videoRelease";
        applicationContext.publishEvent(new VideoEvent(eventDec,bmsVideo,bmsUserVideo,
                bmsDxClientRole.getRoleId(),userDataMap));
    }


    public Map<String, Object> assistantList(Integer userId, Integer businessId, Integer pageNum, Integer pageSize) {
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"new_time");
        List<Map<String,Object>> assistantList = bmsUserBusinessDao.selfFindBusinessIdAndRoleId(businessId,BmsDxClientRoleService.assistantRoleId,pageable);
        List<Map<String,Object>> resultAssistant = getAssistantList(assistantList);
        Map<String,Object> userData = new HashMap<>();
        userData.put("assistantTotal",bmsUserBusinessDao.selfCountBusinessAssistantNum(businessId,BmsDxClientRoleService.assistantRoleId));
        return ResultMapHelper.success(resultAssistant,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    public List<Map<String,Object>> getAssistantList(List<Map<String,Object>> assistantList){
        List<Map<String,Object>> resultAssistantList = new LinkedList<>();
        List<Map<String,Object>> resultAssistant = new LinkedList<>();
        if(assistantList.size() > 0){
            Set<Integer> bmsUserIds = new HashSet<>();
            for(Map<String,Object> assistant : assistantList){
                Map<String,Object> assinstanCopy = new HashMap<>();
                assinstanCopy.putAll(assistant);
                Integer bmsUserId = Integer.parseInt(assistant.get("bms_user_id").toString());
                BmsUser bmsUser = TokenManager.getUser(bmsUserId);
                if(bmsUser != null){
                    assinstanCopy.put("phone",bmsUser.getPhone());
                }
                assinstanCopy.put("AssistantRole",new LinkedList<>());
                resultAssistantList.add(assinstanCopy);
                bmsUserIds.add(bmsUserId);
            }
            if(bmsUserIds.size() > 0){
                Map<Integer,List<Integer>> bmsDxUserPermissionMap = bmsDxUserPermissionService.getUserRole(bmsUserIds,BmsDxClientRoleService.assistantRoleId);
                for(Map<String,Object> assistant : resultAssistantList){
                    Map<String,Object> assinstanCopy = new HashMap<>();
                    assinstanCopy.putAll(assistant);
                    Integer bmsUserId = Integer.parseInt(assistant.get("bms_user_id").toString());
                    if(bmsDxUserPermissionMap.containsKey(bmsUserId)){
                        assinstanCopy.put("AssistantRole",bmsDxUserPermissionMap.get(bmsUserId));
                    }
                    resultAssistant.add(assinstanCopy);
                }
            }
        }
        return resultAssistant;
    }

    @Transactional
    public Map<String, Object> delVideo(Integer userId, Integer businessId, Integer videoId) {
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsVideo bmsVideo = bmsVideoService.checkVideoExist(videoId);
        if(bmsVideo == null){
            return ResultMapHelper.result(ResultCode.CODE_VIDEO_NO_EXIST,"视频不存在");
        }
        if(bmsVideo.getBmsId().intValue() != businessId){
            return ResultMapHelper.result(ResultCode.CODE_VIDEO_NO_BELONG_TO_USER,"视频不属于该用户");
        }
        bmsVideo.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
        bmsVideoService.save(bmsVideo);
        //同时删除发布记录
        /*BmsUserVideo bmsUserVideo = bmsUserVideoService.getBaseDao().findByBmsVideoId(videoId);
        if(bmsUserVideo != null){
            bmsUserVideoService.delete(bmsUserVideo);
        }*/
        return ResultMapHelper.success(bmsVideo,"删除成功");
    }

    public Map<String, Object> checkBusinessIsHaving(Integer userId, Integer businessId) {
        Optional<BmsBusiness> businessOp = bmsBusinessService.getBaseDao().findById(businessId);
        if(!businessOp.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByUserIdNotReject(userId,businessId);
        if(bmsUserBusinessAuth == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_USER_NO_CLAIMED,"请先认领店铺");
        }
        if(bmsUserBusinessAuth.getBmsBusinessId() != businessId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG_USER,"店铺不属于该用户");
        }
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("businessAuth",bmsUserBusinessAuth);
        userDataMap.put("business",bmsUserBusinessAuth.getBmsBusiness());
        return ResultMapHelper.success(businessOp.get(),userDataMap);
    }

    /**
     * @Description 查询店铺是否认证
     * @Param userId
     * @Param businessId
     * @Author: cfx
     * @Date: 2019/9/23
     */
    public Map<String, Object> checkBusinessIsAuth(Integer userId, Integer businessId) {
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        if(business.getIsAuth() != Constants.COMMON_FLAG_TRUE_INT){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_AUTH,ResultMsg.CODE_BUSINESS_NO_AUTH);
        }
        return checkMap;
    }

    public Map<String, Object> getMyOrderHome(Integer userId,Integer businessId) {
        //检验是否是商家或者店员
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        //获取线上买单（线上买单 + 优惠买单）的总成交额
        Set<Integer> orderTypes = new HashSet<>();
        orderTypes.add(Constants.ONLINE_ORDER_TYPE);
        orderTypes.add(Constants.COUPONS_ORDER_TYPE);
        Double onlinePay =  bmsDxOrderService.countOrderTotalByType(businessId,orderTypes,Constants.PAY_COMPLETE);
        //获取团购核销买单的总成交额
        Double groupBuyPay =  bmsDxGroupBuyUseService.countGroupOrderTotal(businessId,Constants.GROUP_ALREADY_USE);
        BusinessOrderHomeRpDto businessOrderHomeRpDto = new BusinessOrderHomeRpDto();
        businessOrderHomeRpDto.setOnlinePay(onlinePay);
        businessOrderHomeRpDto.setGroupBuyPay(groupBuyPay);
        businessOrderHomeRpDto.setTotal(ArithUtil.add(onlinePay,groupBuyPay));
        return ResultMapHelper.success(businessOrderHomeRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 商户端获取订单详情
     * @Author: cfx
     * @Date: 2019/8/1
     */
    public Map<String, Object> getMyOrderByType(BusinessOrderDetailReDto businessOrderDetailReDto) {
        //检验是否是商家
        final int GROUP_BUY_ORDER = 1; //团购订单
        final int PAY_FOR_ORDER = 2; //买单订单
        //今天
        final int TIME_MODEL_ONE = 1;
        //近7天
        final int TIME_MODEL_TWO = 2;
        //近30天
        final int TIME_MODEL_THIRD = 3;
        //全部
        final int TIME_MODEL_FOUR = 4;
        Integer businessId = businessOrderDetailReDto.getBusinessId();
        Integer userId = Integer.parseInt(businessOrderDetailReDto.getUserId());
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        BusinessOrderDetailRpDto businessOrderDetailRpDto = new BusinessOrderDetailRpDto();
        List<BmsDxOrder> bmsDxOrders = new LinkedList<>();
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = new LinkedList<>();
        Date nowTime = new Date();
        Integer startTime = 0;
        Integer endTime = (int)(nowTime.getTime() / 1000);
        //设置时间
        if(businessOrderDetailReDto.getTimeNode() == TIME_MODEL_ONE){
            startTime = (int)(DateTimeUtils.getTodayStart().getTime() / 1000);
            endTime = startTime + 3600 * 24 - 1;
        }else if(businessOrderDetailReDto.getTimeNode() == TIME_MODEL_TWO){
            final int MODEL_DAY = -6;
            startTime = (int)(DateTimeUtils.getStartTimeOfDay(DateTimeUtils.addDay(nowTime,MODEL_DAY)).getTime() / 1000);
        }else if(businessOrderDetailReDto.getTimeNode() == TIME_MODEL_THIRD){
            final int MODEL_DAY = -29;
            startTime = (int)(DateTimeUtils.getStartTimeOfDay(DateTimeUtils.addDay(nowTime,MODEL_DAY)).getTime() / 1000);
        }else if(businessOrderDetailReDto.getTimeNode() == TIME_MODEL_FOUR){
            if(StringUtils.isNotBlank(businessOrderDetailReDto.getSearchStartTime())
                    && StringUtils.isNotBlank(businessOrderDetailReDto.getSearchEndTime())){
                startTime = (int)(DateTimeUtils.converStringToDate(businessOrderDetailReDto.getSearchStartTime()).getTime() / 1000);
                endTime = (int)(DateTimeUtils.converStrToTimestamp(businessOrderDetailReDto.getSearchEndTime() + " 23:59:59").getTime() / 1000);
            }
        }
        //为了和数据库比较做兼容
        String startTimes  = DateTimeUtils.converDateToString(DateTimeUtils.converLongToDate(startTime * 1000L),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        String endTimes = DateTimeUtils.converDateToString(DateTimeUtils.converLongToDate(endTime * 1000L),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        Integer countOrderNum = Constants.COMMON_FLAG_FALSE_INT;
        Double totalNum = (double)Constants.COMMON_FLAG_FALSE_INT;
        Set orderTypes = new HashSet<>();
        if(businessOrderDetailReDto.getOrderType() == GROUP_BUY_ORDER){
            //团购订单
            orderTypes.add(Constants.GROUP_BUY_ORDER_TYPE);
            orderTypes.add(Constants.FX_ORDER_TYPE);
            Set<Integer> useStatuses = new HashSet<>();
            useStatuses.add(Constants.GROUP_ALREADY_USE);
            //核销单数
            countOrderNum = bmsDxGroupBuyUseService.countGroupBuyUseCountByTime(businessId,useStatuses,startTimes,endTimes);
            //核销金额
            totalNum = bmsDxGroupBuyUseService.countGroupBuyUseSumByTime(businessId,useStatuses,startTimes,endTimes);
            //核销列表
            Pageable pageable = BmsCommonService.getPageable(businessOrderDetailReDto.getPageNum(),
                    businessOrderDetailReDto.getPageSize());
            bmsDxGroupBuyUses.addAll(bmsDxGroupBuyUseService.getBaseDao().getGroupBuyUseListByTime(businessId,orderTypes,useStatuses,startTimes,endTimes,pageable));
            //设置团购订单数据
            bmsDxOrderService.setGroupOrder(bmsDxGroupBuyUses);
            List<BusinessOrderDetailRpDto.BmsDxGroupBuyUseVo> bmsDxGroupBuyUseVos = BeanUtils.copyList(bmsDxGroupBuyUses,BusinessOrderDetailRpDto.BmsDxGroupBuyUseVo.class);
            businessOrderDetailRpDto.setGroupBuyOrders(bmsDxGroupBuyUseVos);
            postHandleGroupBuyOrders(businessOrderDetailRpDto.getGroupBuyOrders());
            setCleanDataByGroupBuy(businessOrderDetailRpDto,bmsDxGroupBuyUses);
        }else if(businessOrderDetailReDto.getOrderType() == PAY_FOR_ORDER){
            //买单订单
            orderTypes.add(Constants.ONLINE_ORDER_TYPE);
            orderTypes.add(Constants.COUPONS_ORDER_TYPE);
            //支付状态
            Integer status = Constants.PAY_COMPLETE;
            //查出该商家支付的买单订单
            countOrderNum = bmsDxOrderService.countBusinessOrderNum(businessId,orderTypes,status,
                    startTimes,endTimes);
            //查出多少钱
            totalNum = bmsDxOrderService.countOrderTotalByType(businessId,orderTypes,status,startTimes,endTimes);
            //展示列表
            //查出该商家所有的
            Pageable pageable = BmsCommonService.getPageable(businessOrderDetailReDto.getPageNum(),
                    businessOrderDetailReDto.getPageSize(), Sort.Direction.DESC,"pay_time");

            bmsDxOrders.addAll(bmsDxOrderService.getBaseDao().selfFindOrder(businessId,orderTypes,status,startTimes,endTimes,pageable));
            businessOrderDetailRpDto.setPayOrders(bmsDxOrders);
            bmsDxOrderService.setPayForOrder(bmsDxOrders);
            //设置商家
            bmsDxOrderService.setOrderBusiness(bmsDxOrders);
            //设置消费者
            bmsDxOrderService.setOrderUserName(bmsDxOrders);
            //设置满减券
            bmsDxOrderService.setFullCoupon(bmsDxOrders);
            setCleanDataByPayOrder(businessOrderDetailRpDto,bmsDxOrders);
        }
        businessOrderDetailRpDto.setPayForNum(countOrderNum);
        businessOrderDetailRpDto.setDealAmount(totalNum);
        return ResultMapHelper.success(businessOrderDetailRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 商户端获取订单详情
     * @Author: cfx
     * @Date: 2019/8/1
     */
    public Map<String,Object> getOrderDataForDataBank(GetByBusinessOrderForDataBankDto getByBusinessOrderForDataBankDto) {
        Integer orderType = getByBusinessOrderForDataBankDto.getOrderType();
        Integer pageSize = getByBusinessOrderForDataBankDto.getPageSize();
        Integer pageNum = getByBusinessOrderForDataBankDto.getPageNum();
        final int GROUP_BUY_ORDER = 1; //团购订单
        final int PAY_FOR_ORDER = 2; //买单订单
        Integer businessId = getByBusinessOrderForDataBankDto.getBusinessId();
        BusinessOrderDetailRpDto businessOrderDetailRpDto = new BusinessOrderDetailRpDto();
        List<BmsDxOrder> bmsDxOrders = new LinkedList<>();
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = new LinkedList<>();
        Date nowTime = new Date();
        Set orderTypes = new HashSet<>();
        if(orderType == GROUP_BUY_ORDER){
            //团购订单
            orderTypes.add(Constants.GROUP_BUY_ORDER_TYPE);
            orderTypes.add(Constants.FX_ORDER_TYPE);
            Set<Integer> useStatuses = new HashSet<>();
            useStatuses.add(Constants.GROUP_ALREADY_USE);
            //核销列表
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"use_time");
            bmsDxGroupBuyUses.addAll(bmsDxGroupBuyUseService.getBaseDao().getGroupBuyUseList(businessId,orderTypes,useStatuses,pageable));
            //log.info("bmsDxGroupBuyUses {}" + JSON.toJSONString(bmsDxGroupBuyUses));
            businessOrderDetailRpDto.setCount(bmsDxGroupBuyUseService.getBaseDao().getGroupBuyUseList(businessId,orderTypes,useStatuses));
            //设置团购订单数据
            bmsDxOrderService.setGroupOrder(bmsDxGroupBuyUses);
            List<BusinessOrderDetailRpDto.BmsDxGroupBuyUseVo> bmsDxGroupBuyUseVos = BeanUtils.copyList(bmsDxGroupBuyUses,BusinessOrderDetailRpDto.BmsDxGroupBuyUseVo.class);
            businessOrderDetailRpDto.setGroupBuyOrders(bmsDxGroupBuyUseVos);
            postHandleGroupBuyOrders(businessOrderDetailRpDto.getGroupBuyOrders());
            setCleanDataByGroupBuy(businessOrderDetailRpDto,bmsDxGroupBuyUses);
        }else if(orderType == PAY_FOR_ORDER){
            //买单订单
            orderTypes.add(Constants.ONLINE_ORDER_TYPE);
            orderTypes.add(Constants.COUPONS_ORDER_TYPE);
            //支付状态
            Integer status = Constants.PAY_COMPLETE;
            //展示列表
            //查出该商家所有的
            Pageable pageable = BmsCommonService.getPageable(pageNum,
                    pageSize, Sort.Direction.DESC,"pay_time");

            bmsDxOrders.addAll(bmsDxOrderService.getBaseDao().selfFindOrder(businessId,orderTypes,status,pageable));
            businessOrderDetailRpDto.setPayOrders(bmsDxOrders);
            businessOrderDetailRpDto.setCount(bmsDxOrderService.getBaseDao().selfFindOrder(businessId,orderTypes,status));
            bmsDxOrderService.setPayForOrder(bmsDxOrders);
            //设置商家
            bmsDxOrderService.setOrderBusiness(bmsDxOrders);
            //设置消费者
            bmsDxOrderService.setOrderUserName(bmsDxOrders);
            //设置满减券
            bmsDxOrderService.setFullCoupon(bmsDxOrders);
            setCleanDataByPayOrder(businessOrderDetailRpDto,bmsDxOrders);
        }
        //整理下数据
        return ResultMapHelper.success(businessOrderDetailRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    private void postHandleGroupBuyOrders(List<BusinessOrderDetailRpDto.BmsDxGroupBuyUseVo> groupBuyOrders) {
        if(CollectionUtils.isNotEmpty(groupBuyOrders)){
            groupBuyOrders.forEach(gb -> {
                if(gb.getBmsDxOrder() != null && gb.getBmsDxOrder().getBmsDxGroupBuy() != null){
                    BmsDxGroupBuy bmsDxGroupBuy = gb.getBmsDxOrder().getBmsDxGroupBuy();
                    if(bmsDxGroupBuy.getIsRealTimeAccount() == Constants.COMMON_FLAG_FALSE_INT){
                        gb.setReceivedDesc("线下结算");
                    }
                    if(StringUtils.isNotBlank(bmsDxGroupBuy.getTextContent())){
                        gb.setRichText(bmsDxGroupBuy.getTextContent());
                        bmsDxGroupBuy.setTextContent(null);
                    }
                    if(bmsDxGroupBuy.getIsBusinessConsume() != null){
                        gb.setIsBusinessConsume(bmsDxGroupBuy.getIsBusinessConsume());
                    }
                }
            });
        }
    }

    public void setCleanDataByPayOrder(BusinessOrderDetailRpDto businessOrderDetailRpDto, List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            List<OrderManagerList> orderManagerLists = new LinkedList<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                OrderManagerList orderManagerList = new OrderManagerList();
                BeanUtils.copyProperties(bmsDxOrder,orderManagerList);
                orderManagerList.setGroupBuyId(bmsDxOrder.getBmsGroupBuyId());
                orderManagerList.setShopConsum(bmsDxOrder.getShopConsum());
                orderManagerLists.add(orderManagerList);
                orderManagerList.setOrderId(bmsDxOrder.getId());
                OrderManagerDetail orderManagerDetail = new OrderManagerDetail();
                orderManagerList.setOrderManagerDetail(orderManagerDetail);
                if(bmsDxOrder.getBmsDxCoupon() != null) {
                    orderManagerDetail.setPayContent(bmsDxOrder.getBmsDxCoupon().getPayContent());
                    orderManagerDetail.setType(bmsDxOrder.getBmsDxCoupon().getType());
                    orderManagerDetail.setUseWeekDisplay(bmsDxOrder.getBmsDxCoupon().getUseWeekDisplay());
                }
            }
            businessOrderDetailRpDto.setOrderManagerLists(orderManagerLists);
        }
    }

    public void setCleanDataByGroupBuy(BusinessOrderDetailRpDto businessOrderDetailRpDto, List<BmsDxGroupBuyUse> bmsDxGroupBuyUses){
        if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
            List<OrderManagerList> orderManagerLists = new LinkedList<>();
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                OrderManagerList orderManagerList = new OrderManagerList();
                BeanUtils.copyProperties(bmsDxGroupBuyUse,orderManagerList);
                orderManagerList.setActualConsum(ArithUtil.mul(bmsDxGroupBuyUse.getGbuyActualConsum(),orderManagerList.getAlreadyCancelNum()));
                orderManagerList.setGroupBuyUseId(bmsDxGroupBuyUse.getId());
                orderManagerList.setGroupName(bmsDxGroupBuyUse.getBmsDxOrder().getBmsDxGroupBuy().getGroupName());
                orderManagerLists.add(orderManagerList);
                BmsDxOrder bmsDxOrder = bmsDxGroupBuyUse.getBmsDxOrder();
                BeanUtils.copyProperties(bmsDxOrder,orderManagerList);
                //设置特殊的
                orderManagerList.setShopConsum(bmsDxGroupBuyUse.getOnceShopMoney());
                orderManagerList.setDiscountConsum(bmsDxGroupBuyUse.getDiscountMoney());
                orderManagerList.setUseCardMoney(ArithUtil.mul(bmsDxGroupBuyUse.getBackCacdMoney(),orderManagerList.getAlreadyCancelNum()));
                if(bmsDxOrder.getBmsDxGroupBuy() != null){
                    BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                    if(bmsDxGroupBuy.getIsBusinessConsume() != null){
                        orderManagerList.setIsBusinessConsume(bmsDxGroupBuy.getIsBusinessConsume());
                    }
                }
                //设置使用优惠券
                Double discountConsum = ArithUtil.mul(bmsDxGroupBuyUse.getDiscountMoney(),orderManagerList.getAlreadyCancelNum());
                Double useCardMoney = ArithUtil.mul(bmsDxGroupBuyUse.getBackCacdMoney(),orderManagerList.getAlreadyCancelNum());
                orderManagerList.setUseCoupons(ArithUtil.sub(discountConsum,useCardMoney));
                OrderManagerDetail orderManagerDetail = new OrderManagerDetail();
                orderManagerList.setOrderManagerDetail(orderManagerDetail);
                BeanUtils.copyProperties(bmsDxOrder.getBmsDxGroupBuy(),orderManagerDetail);
                orderManagerDetail.setVerManName(bmsDxGroupBuyUse.getNickName());
            }
            businessOrderDetailRpDto.setOrderManagerLists(orderManagerLists);
        }
    }

    public Map<String,Object> checkBusinessIsHavingOrAssistant(Integer userId, Integer businessId) {
        BmsBusiness business;
        Map<String,Object> checkMap = this.checkBusinessIsHaving(userId,businessId);
        if(ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            business = (BmsBusiness) checkMap.get("data");
        }else {
            //判断是否是店员
            if(!this.checkBusinessIsAssistan(userId,businessId)){
                return checkMap;
            }
            business = bmsBusinessService.getBaseDao().findById(businessId).get();
        }
        return ResultMapHelper.success(business);
    }

    public Map<String,Object> checkBusinessUserAuth(Integer userId, Integer businessId,Integer permissionCode) {
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        //检验权限
        Set<Integer> roleIds = new HashSet<>();
        roleIds.add(Constants.BUSINESS_ROLE_ID);
        roleIds.add(Constants.ASSISTANT_ROLE_ID);
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getUserClienRole(userId,roleIds);
        if(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0){
            BmsDxClientRole bmsDxClientRole = bmsDxClientRoles.get(0);
            if(bmsDxClientRole.getRoleId() == Constants.ASSISTANT_ROLE_ID){
                List<BmsDxUserPermission> bmsDxUserPermission = bmsDxUserPermissionService.getBaseDao().findByBmsUserIdAndRoleIdAndBmsPermissionId(userId,bmsDxClientRole.getRoleId(),Constants.GROUP_CHAT_PERMISSION);
                if(!(bmsDxUserPermission != null && bmsDxUserPermission.size() > 0)){
                    return ResultMapHelper.result(ResultCode.CODE_ERROR_110,ResultMsg.CODE_ERROR_110);
                }
            }
        }
        return checkMap;
    }

    public Map<Integer,BmsUserBusiness> getAssistantMap(Set<Integer> assistantIds){
        Map<Integer,BmsUserBusiness> resultMap = new HashMap<>();
        if(assistantIds.size() > 0) {
            Map<String, Object> conditionMap = new HashMap<>();
            conditionMap.put("bmsUserId_IN", assistantIds);
            List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findAll(new SpecificationUtils(conditionMap));
            if (bmsUserBusinesses != null && bmsUserBusinesses.size() > 0){
                for(BmsUserBusiness bmsUserBusiness : bmsUserBusinesses){
                    resultMap.put(bmsUserBusiness.getBmsUserId(),bmsUserBusiness);
                }
            }
        }
        return resultMap;
    }

    /**
     * @Description 获取商家消费用户
     * @Param:  map
     * @Author: cfx
     * @Date: 2019/8/6
     */
    public Map<String, Object> getMyConsumerUsers(Map<String, Object> paramsMap) {
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());
        Integer pageNum = Integer.parseInt(paramsMap.get("pageNum").toString());
        Integer businessId = Integer.parseInt(paramsMap.get("businessId").toString());
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize);
        List<Map> consumerUsers = bmsDxOrderStatusService.getBusinessConsumerUsers(businessId,pageable);
        List<ConsumerUserRpDto> consumerUserRpDtos = setConsumerUser(consumerUsers);
        //查询所有消费者
        List<Map> allConsumerUsers = bmsDxOrderStatusService.getBusinessConsumerUsers(businessId);
        Map<String,Object> userData = new HashMap<>();
        userData.put("consumerUsersNum",allConsumerUsers.size());
        return ResultMapHelper.success(consumerUserRpDtos,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    List<ConsumerUserRpDto> setConsumerUser(List<Map> consumerUsers){
        List<ConsumerUserRpDto> consumerUserRpDtos = new LinkedList<>();
        if(consumerUsers != null && consumerUsers.size() > 0){
            for(Map<String,Object> consumerUser : consumerUsers){
                ConsumerUserRpDto consumerUserRpDto = new ConsumerUserRpDto();
                consumerUserRpDto.setBms_user_id(Integer.parseInt(consumerUser.get("userId").toString()));
                consumerUserRpDto.setConsumerNum(Integer.parseInt(consumerUser.get("num").toString()));
                consumerUserRpDto.setConsumerTotal(consumerUser.get("total").toString());
                BmsUser bmsUser = TokenManager.getUser(consumerUserRpDto.getBms_user_id());
                if(bmsUser != null){
                    if(StringUtils.isNotBlank(bmsUser.getLoginName())){
                        consumerUserRpDto.setLogin_name(bmsUser.getLoginName());
                    }
                    if(StringUtils.isNotBlank(bmsUser.getHeadImg())){
                        consumerUserRpDto.setHead_img(bmsUser.getHeadImg());
                    }
                }
                consumerUserRpDtos.add(consumerUserRpDto);
            }
        }
        return consumerUserRpDtos;
    }

    /**
     * @Description 用于登录过后获取登录信息
     * @Author: cfx
     * @Date: 2019/9/12
     */
    public Map<String, Object> getLoginBusinessData(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        BmsUserBusinessRpDto bmsUserBusinessRpDto = new BmsUserBusinessRpDto();
        bmsUserBusinessRpDto.setBusinessRole(noUserBusinessType);
        bmsUserBusinessRpDto.setIsHavingBusiness(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessRpDto.setIsOpenCoupon(Constants.COMMON_FLAG_FALSE_INT);
        bmsUserBusinessRpDto.setIsFirstLogin(Constants.COMMON_FLAG_FALSE_INT);
        BmsUser bmsUser = TokenManager.getUser(userId);
        try {
            handleBmsUserBusinessRpDto(bmsUserBusinessRpDto,bmsUser,businessId);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultMapHelper.result(ResultCode.CODE_ERROR,ResultMsg.HAND_FAIL);
        }
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        int client = requestHeaderData.getInteger("client");
        /*String redisKey = Constants.REDIS_KEY_TOKEN + bmsUserBusinessRpDto.getUserid() + ":" + Constants.BUSINESS_CLIENT + ":" + client;
        if(!RedisTemplateUtils.getRedisTemplate().hasKey(redisKey)){
            return ResultMapHelper.result(ResultCode.USER_TOKEN_INVALID,"token失效");
        }*/
        //bmsUserBusinessRpDto.setToken(RedisTemplateUtils.getRedisTemplate().opsForValue().get(redisKey).toString());
        bmsUserBusinessRpDto.setToken(TokenUtils.getToken(userId.toString(),String.valueOf(Constants.DXSH_ROLE_ID),false));
        if(bmsUser.getIdeUse() != null){
            if(bmsUser.getIdeUse() == Constants.USER_IDENT_MT){
                bmsUserBusinessRpDto.setIsNoCertShowMt(Constants.COMMON_FLAG_TRUE_INT);
            }
        }
        return ResultMapHelper.success(bmsUserBusinessRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 统计店员数
     * @Param businessId
     * @Author: cfx
     * @Date: 2019/9/23
     */
    public Integer countMyBusinessAssistant(Integer businessId) {
        return bmsUserBusinessDao.selfCountBusinessAssistantNum(businessId,BmsDxClientRoleService.assistantRoleId);
    }

    public Set<Integer> findUserHavingBusiness(Integer userId) {
        Set<Integer> buinessIds = new HashSet<>();
        List<BmsUserBusinessAuth> bmsUserBusinessAuths = bmsUserBusinessAuthService.findAllBusinessByUserId(userId);
        BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuthService.findByUserId(userId);
        if(bmsUserBusinessAuths != null && bmsUserBusinessAuths.size() > 0){
            buinessIds.addAll(bmsUserBusinessAuths.stream().map(BmsUserBusinessAuth::getBmsBusinessId).collect(Collectors.toSet()));
            return buinessIds;
        }
        //店员
        List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessDao.findByBmsUserId(userId);
        if(bmsUserBusinesses != null && bmsUserBusinesses.size() > 0){
            buinessIds.add(bmsUserBusinesses.get(0).getBmsBusinessId());
            return buinessIds;
        }
        return null;
    }

    public Map<String, Object>  searchCode(ParamsMap paramsMap) {
        //设置前端识别，已退款
        final int REFUND_CODE = 3;
        Integer businessId = paramsMap.getInteger("buinessId");
        String code = paramsMap.getString("code");
        //购买券
        final int GROUP_BUY_CODE = 1;
        //领取券
        final int GET_COUPON = 2;
        Map<String,Object> userDataMap = new HashMap<>();
        GroupBuyUseReDto groupBuyUseReDto = new GroupBuyUseReDto();
        groupBuyUseReDto.setSearchGroupUseCode(code);
        groupBuyUseReDto.setPageNum(1);
        groupBuyUseReDto.setPageSize(1);
        Integer notTime = DateTimeUtils.getNowTimeStamp();
        BmsDxGroupBuyUse bmsDxGroupBuyUse = bmsDxGroupBuyUseService.getGroupByCode(code);
        if(bmsDxGroupBuyUse != null){
            Optional<BmsDxGroupBuy> bmsDxGroupBuyOptional = bmsDxGroupBuyService.getBaseDao().findById(bmsDxGroupBuyUse.getGroupBuyId());
            if(bmsDxGroupBuyOptional.isPresent()){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyOptional.get();
                bmsDxGroupBuyService.postHandleBusiness(bmsDxGroupBuy);
                bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuy);
                userDataMap.put("codeType",GROUP_BUY_CODE);
                userDataMap.put("havingData",Constants.COMMON_FLAG_TRUE_INT);
                userDataMap.put("couponType",null);
                SearchCodeRpDto searchCodeRpDto = new SearchCodeRpDto();
                searchCodeRpDto.setBmsBusiness(bmsDxGroupBuy.getBmsBusiness());
                searchCodeRpDto.setCodes(new ArrayList<>());
                searchCodeRpDto.setCouponName(bmsDxGroupBuy.getGroupName());
                searchCodeRpDto.setExpireTime(bmsDxGroupBuy.getExpireTime());
                searchCodeRpDto.setBmsDxGroupBuy(bmsDxGroupBuy);
                if(StringUtils.isNotBlank(bmsDxGroupBuy.getTextContent())){
                    searchCodeRpDto.setRichText(bmsDxGroupBuy.getTextContent());
                    bmsDxGroupBuy.setTextContent(null);
                }
                if(bmsDxGroupBuy.getIsRealTimeAccount() == Constants.COMMON_FLAG_FALSE_INT){
                    searchCodeRpDto.setReceivedDesc(SearchCodeRpDto.RICH_TEXT_OFFLINE_TEXT);
                }
                List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getGroupByCodeOrderNoUse(bmsDxGroupBuyUse.getOrderId());
                if(CollectionUtils.isNotEmpty(bmsDxGroupBuyUses)) {
                    bmsDxGroupBuyUses.forEach(by -> {
                        Code rpCode = new Code();
                        rpCode.setStatus(by.getStatus());
                        if (rpCode.getStatus() == Constants.GROUP_REFUND_COMPLETE) {
                            rpCode.setStatus(REFUND_CODE);
                        }
                        if (rpCode.getStatus() == Constants.GROUP_NO_USE && bmsDxGroupBuy.getExpireTime() != null) {
                            if (DateTimeUtils.addDay(DateTimeUtils.converDateToInterger(bmsDxGroupBuy.getExpireTime()),1) <= notTime) {
                                rpCode.setStatus(Constants.IS_OVER_EXPIRE);
                            }
                        }
                        rpCode.setCodeNumber(by.getGroupBuyCode());
                        searchCodeRpDto.getCodes().add(rpCode);
                    });
                }
                return ResultMapHelper.success(searchCodeRpDto,userDataMap,ResultMsg.MSG_GET_SUCCESS);
            }
        }
        /*Map<String,Object> groupBuyUseMap = bmsDxGroupBuyUseService.userGetGroupBuyUse(groupBuyUseReDto);
        if(groupBuyUseMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(groupBuyUseMap.get("status").toString())){
            List<UserGroupBuyUseRpDto> buyUseRpDtos = (List<UserGroupBuyUseRpDto>) groupBuyUseMap.get("data");
            if(buyUseRpDtos != null && buyUseRpDtos.size() > 0){
                UserGroupBuyUseRpDto groupBuyUseRpDto = buyUseRpDtos.get(0);
                userDataMap.put("codeType",GROUP_BUY_CODE);
                userDataMap.put("havingData",Constants.COMMON_FLAG_TRUE_INT);
                userDataMap.put("couponType",null);
                SearchCodeRpDto searchCodeRpDto = new SearchCodeRpDto();
                searchCodeRpDto.setBmsBusiness(groupBuyUseRpDto.getBmsDxGroupBuy().getBmsBusiness());
                searchCodeRpDto.setCodes(new ArrayList<>());
                searchCodeRpDto.setCouponName(groupBuyUseRpDto.getBmsDxGroupBuy().getGroupName());
                searchCodeRpDto.setExpireTime(groupBuyUseRpDto.getBmsDxGroupBuy().getExpireTime());
                searchCodeRpDto.setBmsDxGroupBuy(groupBuyUseRpDto.getBmsDxGroupBuy());
                if(searchCodeRpDto.getBmsDxGroupBuy() != null){
                    BmsDxGroupBuy bmsDxGroupBuy = searchCodeRpDto.getBmsDxGroupBuy();
                    if(StringUtils.isNotBlank(bmsDxGroupBuy.getTextContent())){
                        searchCodeRpDto.setRichText(bmsDxGroupBuy.getTextContent());
                        bmsDxGroupBuy.setTextContent(null);
                    }
                    if(bmsDxGroupBuy.getIsRealTimeAccount() == Constants.COMMON_FLAG_FALSE_INT){
                        searchCodeRpDto.setReceivedDesc(SearchCodeRpDto.RICH_TEXT_OFFLINE_TEXT);
                    }
                }
                if(groupBuyUseRpDto.getBmsDxGroupBuyUse() != null && groupBuyUseRpDto.getBmsDxGroupBuyUse().size() > 0){
                    for(BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseRpDto.getBmsDxGroupBuyUse()){
                        Code rpCode = new Code();
                        rpCode.setStatus(bmsDxGroupBuyUse.getStatus());
                        if(rpCode.getStatus() == Constants.GROUP_REFUND_COMPLETE){
                            rpCode.setStatus(REFUND_CODE);
                        }

                        if(rpCode.getStatus() == Constants.GROUP_NO_USE && groupBuyUseRpDto.getBmsDxGroupBuy().getExpireTime() != null){
                            if(DateTimeUtils.converDateToInterger(groupBuyUseRpDto.getBmsDxGroupBuy().getExpireTime()) <= notTime){
                                rpCode.setStatus(Constants.IS_OVER_EXPIRE);
                            }
                        }
                        rpCode.setCodeNumber(bmsDxGroupBuyUse.getGroupBuyCode());
                        searchCodeRpDto.getCodes().add(rpCode);
                    }
                }
                return ResultMapHelper.success(searchCodeRpDto,userDataMap,ResultMsg.MSG_GET_SUCCESS);
            }
        }*/
        //查询领取券
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("consumerCode",code);
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            bmsUserReceCouponService.setBmsUserReceCoupon(bmsUserReceCoupons);
            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCoupons.get(0);
            userDataMap.put("codeType",GET_COUPON);
            userDataMap.put("havingData",Constants.COMMON_FLAG_TRUE_INT);
            //整理数据
            Code rpCode = new Code();
            rpCode.setStatus(bmsUserReceCoupon.getStatus());
            rpCode.setCodeNumber(bmsUserReceCoupon.getConsumerCode());
            SearchCodeRpDto searchCodeRpDto = new SearchCodeRpDto();
            searchCodeRpDto.setCodes(new ArrayList<>());
            searchCodeRpDto.getCodes().add(rpCode);
            BusinessRpDto businessRpDto = new BusinessRpDto();
            BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsUserReceCoupon.getBusinessId());
            if(bmsBusiness != null) {
                org.springframework.beans.BeanUtils.copyProperties(bmsBusiness,businessRpDto);
            }
            searchCodeRpDto.setBmsBusiness(businessRpDto);
            searchCodeRpDto.setCouponName(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponName());
            searchCodeRpDto.setExpireTime(bmsUserReceCoupon.getExpireTime());
            searchCodeRpDto.setBmsUserReceCoupon(bmsUserReceCoupon);
            searchCodeRpDto.setBmsBusinessCoupon(bmsUserReceCoupon.getBmsBusinessCoupon());
            userDataMap.put("couponType",bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType());
            return ResultMapHelper.success(searchCodeRpDto,userDataMap,ResultMsg.MSG_GET_SUCCESS);
        }
        //都没查到
        userDataMap.put("codeType",null);
        userDataMap.put("havingData",Constants.COMMON_FLAG_FALSE_INT);
        return ResultMapHelper.success(null,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String, Object> getMyBusinessList(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("bmsUserId",userId);
        Sort sort = Sort.by(Sort.Direction.ASC,"newTimes");
        List<BmsUserBusinessAuth> bmsUserBusinessAuths = bmsUserBusinessAuthService.getBaseDao().findAll(new SpecificationUtils(conditionMap),sort);
        Map<String, Object> userData = new HashMap<>();
        if(bmsUserBusinessAuths != null && bmsUserBusinessAuths.size() > 0) {
            BmsUserBusinessAuth bmsUserBusinessAuth = bmsUserBusinessAuths.get(0);
            userData.put("businessNum",bmsUserBusinessAuthService.getBaseDao().count(new SpecificationUtils(conditionMap)));
            userData.put("logoUrl",bmsUserBusinessAuth.getBmsBusiness().getLogoUrl());
            userData.put("vendorName",bmsUserBusinessAuth.getBmsBusiness().getVendorName());
        }
        return ResultMapHelper.success(bmsUserBusinessAuths,userData,ResultMsg.MSG_GET_SUCCESS);


    }

    public Map<String, Object> getMyEarnings(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("todayTotal",0d);
        resultMap.put("weekTotal",0d);
        resultMap.put("monthTotal",0d);
        Integer businessId = paramsMap.getInteger("businessId");
        if(businessId == null){
            return resultMap;
        }
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return resultMap;
        }
        //订单类型
        Set<Integer> orderTypes = new HashSet<>();
        orderTypes.add(Constants.ONLINE_ORDER_TYPE);
        orderTypes.add(Constants.COUPONS_ORDER_TYPE);
        //团购使用状态
        Set<Integer> useStatuses = new HashSet<>();
        useStatuses.add(Constants.GROUP_ALREADY_USE);

        Date nowTime = new Date();
        //String startTimes  = DateTimeUtils.converDateToString(DateTimeUtils.converLongToDate(startTime * 1000L),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        //当天
        String startTimes = DateTimeUtils.converDateToString(DateTimeUtils.getStartTimeOfDay(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        String endTimes = DateTimeUtils.converDateToString(DateTimeUtils.getEndTimeOfDay(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        //买单订单
        Double sellOrderTotal = bmsDxOrderService.countOrderTotalByType(businessId,orderTypes,Constants.PAY_COMPLETE,startTimes,endTimes);
        //团购订单金额
        Double verOrderTotal = bmsDxGroupBuyUseService.countGroupBuyUseSumByTime(businessId,useStatuses,startTimes,endTimes);
        resultMap.put("todayTotal",ArithUtil.round(ArithUtil.add(sellOrderTotal,verOrderTotal),2));

        //当周
        startTimes = DateTimeUtils.converDateToString(DateTimeUtils.getFirstDayOfWeek(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        endTimes = DateTimeUtils.converDateToString(DateTimeUtils.getLastDayOfWeek(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        //买单订单
        sellOrderTotal = bmsDxOrderService.countOrderTotalByType(businessId,orderTypes,Constants.PAY_COMPLETE,startTimes,endTimes);
        //团购订单金额
        verOrderTotal = bmsDxGroupBuyUseService.countGroupBuyUseSumByTime(businessId,useStatuses,startTimes,endTimes);
        resultMap.put("weekTotal",ArithUtil.round(ArithUtil.add(sellOrderTotal,verOrderTotal),2));

        //当月
        startTimes = DateTimeUtils.converDateToString(DateTimeUtils.getFirstDayOfMonth(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        endTimes = DateTimeUtils.converDateToString(DateTimeUtils.getLastDayOfMonth(nowTime),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
        sellOrderTotal = bmsDxOrderService.countOrderTotalByType(businessId,orderTypes,Constants.PAY_COMPLETE,startTimes,endTimes);
        verOrderTotal = bmsDxGroupBuyUseService.countGroupBuyUseSumByTime(businessId,useStatuses,startTimes,endTimes);
        resultMap.put("monthTotal",ArithUtil.round(ArithUtil.add(sellOrderTotal,verOrderTotal),2));
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String, Object> getMyVerRecord(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Integer pageSzie = paramsMap.getInteger("pageSize");
        Integer pageNum = paramsMap.getInteger("pageNum");
        String endTimes = paramsMap.getString("endTime");
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Map<String,Object> userData = new HashMap<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId",businessId);
        if(StringUtils.isNotBlank(endTimes)){
            Date endTime = DateTimeUtils.getEndTimeOfDay(DateTimeUtils.converLongToDate(Long.parseLong(endTimes)));
            conditionMap.put("verTime_LTT",endTime);
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSzie, Sort.Direction.DESC,"verTime");
        Page<BmsBusinessVerRecord> verRecordPage = bmsBusinessVerRecordService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable);
        userData.put("count",verRecordPage.getTotalElements());
        List<BmsBusinessVerRecord> bmsBusinessVerRecords = verRecordPage.getContent();
        List<VerRecordRpDto> verRecordRpDtos = new LinkedList<>();
        if(bmsBusinessVerRecords != null && bmsBusinessVerRecords.size() > 0){
            for(BmsBusinessVerRecord bmsBusinessVerRecord : bmsBusinessVerRecords){
                VerRecordRpDto verRecordRpDto = new VerRecordRpDto();
                BeanUtils.copyProperties(bmsBusinessVerRecord,verRecordRpDto);
                verRecordRpDto.setVerRecordId(bmsBusinessVerRecord.getId());
                if(verRecordRpDto.getType() == BmsBusinessVerRecordService.TYPE_BUY_COUPON){
                    Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(bmsBusinessVerRecord.getOrderId());
                    if(bmsDxOrderOptional.isPresent()){
                        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
                        verRecordRpDto.setCouponImg(bmsDxOrder.getBmsDxGroupBuy().getGroupImg());
                    }
                }else if(verRecordRpDto.getType() == BmsBusinessVerRecordService.TYPE_RECE_COUPON){
                    Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(bmsBusinessVerRecord.getReceId());
                    if(bmsUserReceCouponOptional.isPresent()){
                        BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
                        if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                            if(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType() == Constants.BUSINESS_COUPON_GROUP_BUY){
                                Map<String,Object> content = JSON.parseObject(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponContent());
                                verRecordRpDto.setCouponImg(content.get("groupImg").toString());
                            }
                        }
                        verRecordRpDto.setCouponType(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType());
                    }
                }
                verRecordRpDtos.add(verRecordRpDto);
            }
        }
        return ResultMapHelper.success(verRecordRpDtos,userData,ResultMsg.MSG_GET_SUCCESS);
    }


    public Map<String, Object> getMyVerRecordByTime(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Integer startTime = paramsMap.getInteger("startTime");
        Integer endTime = paramsMap.getInteger("endTime");
        Map<String,Object> checkMap = this.checkBusinessIsHavingOrAssistant(userId,businessId);;
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("businessId",businessId);
        conditionMap.put("verTime_GTTE",DateTimeUtils.converIntegerToDate(startTime));
        conditionMap.put("verTime_LTT",DateTimeUtils.converIntegerToDate(endTime));
        Sort sort = Sort.by(Sort.Direction.DESC,"verTime");
        List<BmsBusinessVerRecord> bmsBusinessVerRecords = bmsBusinessVerRecordService.getBaseDao().findAll(new SpecificationUtils(conditionMap),sort);
        List<VerRecordRpDto> verRecordRpDtos = new LinkedList<>();
        if(bmsBusinessVerRecords != null && bmsBusinessVerRecords.size() > 0){
            for(BmsBusinessVerRecord bmsBusinessVerRecord : bmsBusinessVerRecords){
                VerRecordRpDto verRecordRpDto = new VerRecordRpDto();
                BeanUtils.copyProperties(bmsBusinessVerRecord,verRecordRpDto);
                verRecordRpDto.setVerRecordId(bmsBusinessVerRecord.getId());
                if(verRecordRpDto.getType() == BmsBusinessVerRecordService.TYPE_BUY_COUPON){
                    Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(bmsBusinessVerRecord.getOrderId());
                    if(bmsDxOrderOptional.isPresent()){
                        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
                        verRecordRpDto.setCouponImg(bmsDxOrder.getBmsDxGroupBuy().getGroupImg());
                    }
                }else if(verRecordRpDto.getType() == BmsBusinessVerRecordService.TYPE_RECE_COUPON){
                    Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(bmsBusinessVerRecord.getReceId());
                    if(bmsUserReceCouponOptional.isPresent()){
                        BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
                        if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                            if(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType() == Constants.BUSINESS_COUPON_GROUP_BUY){
                                Map<String,Object> content = JSON.parseObject(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponContent());
                                verRecordRpDto.setCouponImg(content.get("groupImg").toString());
                            }
                        }
                        verRecordRpDto.setCouponType(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType());
                    }
                }
                verRecordRpDtos.add(verRecordRpDto);
            }
        }
        return ResultMapHelper.success(verRecordRpDtos,ResultMsg.MSG_GET_SUCCESS);
    }

    public String findNameInStoreByUserId(Integer verUserId,Integer businessId) {
        Set<Integer> roleIds = new HashSet<>();
        roleIds.add(Constants.BUSINESS_ROLE_ID);
        roleIds.add(Constants.ASSISTANT_ROLE_ID);
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getUserClienRole(verUserId,roleIds);
        if(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0){
            BmsDxClientRole bmsDxClientRole = bmsDxClientRoles.get(0);
            if(bmsDxClientRole.getRoleId() == Constants.ASSISTANT_ROLE_ID){
                List<BmsUserBusiness> bmsUserBusiness = bmsUserBusinessDao.findByBmsUserIdAndBmsBusinessId(verUserId,businessId);
                if(bmsUserBusiness != null && bmsUserBusiness.size() > 0){
                    return String.format("店员-%s",bmsUserBusiness.get(0).getNameInStore());
                }
            }else {
                return "管理员";
            }
        }
        return null;
    }

    public Map<String, Object> getVerRecordDetails(ParamsMap paramsMap) {
        GetVerRecordDetailsRpVo getVerRecordDetailsRpVo = new GetVerRecordDetailsRpVo();
        Integer verRecordId = paramsMap.getInteger("verRecordId");
        Optional<BmsBusinessVerRecord> bmsBusinessVerRecordOptional = bmsBusinessVerRecordService.getBaseDao().findById(verRecordId);
        if(bmsBusinessVerRecordOptional.isPresent()){
            BmsBusinessVerRecord bmsBusinessVerRecord = bmsBusinessVerRecordOptional.get();
            BmsBusiness bmsBusiness = bmsBusinessService.getBusinessById(bmsBusinessVerRecord.getBusinessId());
            bmsBusinessVerRecord.setBmsBusiness(bmsBusiness);
            if(bmsBusinessVerRecord.getType() == BmsBusinessVerRecordService.TYPE_BUY_COUPON){
                Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(bmsBusinessVerRecord.getOrderId());
                if(bmsDxOrderOptional.isPresent()){
                    BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
                    bmsBusinessVerRecord.setBmsDxGroupBuy(bmsDxOrder.getBmsDxGroupBuy());
                    List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
                    bmsDxGroupBuys.add(bmsDxOrder.getBmsDxGroupBuy());
                    bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
                    bmsBusinessVerRecord.setUserName(BmsUserService.getLoginName(TokenManager.getUser(bmsDxOrder.getBmsUserId())));
                    bmsBusinessVerRecord.setExpireTime(bmsDxOrder.getBmsDxGroupBuy().getExpireTime());
                    Map<String,Object> countData = bmsDxGroupBuyUseService.countMoneyData(bmsBusinessVerRecord.getOrderId(),bmsBusinessVerRecord.getVerTime());
                    getVerRecordDetailsRpVo.setOrderNo(countData.get("orderNo").toString());
                    getVerRecordDetailsRpVo.setUserPay(Double.parseDouble(countData.get("gac").toString()));
                    getVerRecordDetailsRpVo.setDiscountMoney(Double.parseDouble(countData.get("dm").toString()));
                    getVerRecordDetailsRpVo.setShopMoney(Double.parseDouble(countData.get("sm").toString()));
                }
            }else if(bmsBusinessVerRecord.getType() == BmsBusinessVerRecordService.TYPE_RECE_COUPON){
                Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(bmsBusinessVerRecord.getReceId());
                if(bmsUserReceCouponOptional.isPresent()){
                    BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
                    List<BmsUserReceCoupon> bmsUserReceCoupons = new ArrayList<>();
                    bmsUserReceCoupons.add(bmsUserReceCoupon);
                    bmsUserReceCouponService.setBmsUserReceCoupon(bmsUserReceCoupons);
                    bmsBusinessVerRecord.setBmsBusinessCoupon(bmsUserReceCoupon.getBmsBusinessCoupon());
                    bmsBusinessVerRecord.setUserName(BmsUserService.getLoginName(TokenManager.getUser(bmsUserReceCoupon.getUserId())));
                    bmsBusinessVerRecord.setExpireTime(bmsUserReceCoupon.getExpireTime());
                }
            }
            BeanUtils.copyProperties(bmsBusinessVerRecord,getVerRecordDetailsRpVo);
            if(getVerRecordDetailsRpVo.getBmsDxGroupBuy() != null){
                getVerRecordDetailsRpVo.setRichText(getVerRecordDetailsRpVo.getBmsDxGroupBuy().getTextContent());
                getVerRecordDetailsRpVo.getBmsDxGroupBuy().setTextContent(null);
                Integer isRealTimeAccount = getVerRecordDetailsRpVo.getBmsDxGroupBuy().getIsRealTimeAccount();
                if(isRealTimeAccount == Constants.COMMON_FLAG_FALSE_INT){
                    getVerRecordDetailsRpVo.setReceivedDesc("线下结算");
                }
            }
            return ResultMapHelper.success(getVerRecordDetailsRpVo,ResultMsg.MSG_GET_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }

    public Double getBusinessTodayEarByBusiness(Set<Integer> businessIds,String startTimes,String endTimes) {
        //查出当前用户的所有店铺
        if(businessIds.size() > 0) {
            Date nowTime = new Date();
            Set<Integer> orderTypes = new HashSet<>();
            orderTypes.add(Constants.ONLINE_ORDER_TYPE);
            orderTypes.add(Constants.COUPONS_ORDER_TYPE);
            //买单订单
            Double sellOrderTotal = bmsDxOrderService.countOrderTotalByType(businessIds, orderTypes, Constants.PAY_COMPLETE, startTimes, endTimes);
            Set<Integer> useStatuses = new HashSet<>();
            useStatuses.add(Constants.GROUP_ALREADY_USE);
            //团购订单金额
            Double verOrderTotal = bmsDxGroupBuyUseService.countGroupBuyUseSumByTime(businessIds, useStatuses, startTimes, endTimes);
            return ArithUtil.add(sellOrderTotal,verOrderTotal);
        }
        return 0d;
    }

    public Integer getBusinessTodayVerByBusiness(Set<Integer> businessIds,String startTimes,String endTimes) {
        Set<Integer> useStatuses = new HashSet<>();
        useStatuses.add(Constants.GROUP_ALREADY_USE);
        Integer countOrderNum = bmsDxGroupBuyUseService.countGroupBuyUseCountByTime(businessIds,useStatuses,startTimes,endTimes);
        return countOrderNum;
    }

    public void assistantForceLogout(Integer assistantId) {
        String userTokenKey = Constants.REDIS_KEY_TOKEN + String.format("%s:%s:%s",assistantId, Constants.DXSH_ROLE_ID,Constants.APP_CLIENT);
        TokenUtils.cancellation(userTokenKey);
        userTokenKey = Constants.REDIS_KEY_TOKEN + String.format("%s:%s:%s",assistantId, Constants.ASSISTANT_ROLE_ID,Constants.APP_CLIENT);
        TokenUtils.cancellation(userTokenKey);
    }


}
